Note: Our POL balance display is temporarily unavailable. Please check back later.
Source Code
Overview
POL Balance
The POL balance display is temporarily unavailable. Please check back later.
More Info
ContractCreator
Multichain Info
N/A
Latest 4 internal transactions
Parent Transaction Hash | Block | From | To | |||
---|---|---|---|---|---|---|
15966803 | 28 days ago | Contract Creation | 0 POL | |||
15564530 | 38 days ago | Contract Creation | 0 POL | |||
14392293 | 68 days ago | Contract Creation | 0 POL | |||
13055241 | 101 days ago | Contract Creation | 0 POL |
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 Name:
MarketMakerFactory
Compiler Version
v0.8.19+commit.7dd6d404
Optimization Enabled:
Yes with 600 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol"; import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import { IMarketFactory, IMarketFactoryV1_2, IMarketFactoryV1_3, IERC165 } from "./IMarketFactory.sol"; import { IMarketMakerV1, IMarketMakerV1_2, MarketMaker, MarketAddressParams, FeeDistributor } from "./MarketMaker.sol"; import { MarketErrors } from "./MarketErrors.sol"; import { ConditionID, QuestionID, ConditionalTokensErrors, PackedPrices } from "../conditions/IConditionalTokensV1_2.sol"; import { IConditionOracleV1_2 } from "../conditions/IConditionOracleV1_2.sol"; import { AdminExecutorAccessUpgradeable } from "../AdminExecutorAccess.sol"; import { IParlayConditionalTokens, ParlayLegs } from "../conditions/IParlayConditionalTokens.sol"; import { ArrayMath } from "../Math.sol"; contract MarketMakerFactory is MarketErrors, ConditionalTokensErrors, IMarketFactoryV1_3, AdminExecutorAccessUpgradeable { using ArrayMath for uint256[]; using SafeERC20 for IERC20Metadata; using Address for address; using ERC165Checker for address; address private immutable marketTemplate; bytes4 private constant ICONDITION_ORACLE_INTERFACE_ID = 0x7d5f49fa; /// @dev Create a permissioned market factory. Not meant to be upgradeable /// @custom:oz-upgrades-unsafe-allow constructor constructor(FeeDistributor feeDistributor, address admin, address executor) { marketTemplate = address(new MarketMaker(feeDistributor)); initialize(admin, executor); } /// @notice Idempotent creation function, that also creates the condition /// @dev If market has already been created, the event will not be emitted! function createMarket(uint256 fee, MarketAddressParams calldata addresses, PackedPriceMarketParams memory params) public onlyExecutor returns (IMarketMakerV1) { // Leave 1 extra outcome slot for refund outcome uint256 outcomeSlotCount = PackedPrices.arrayLength(params.packedPrices) + 1; if (outcomeSlotCount <= 1) revert InvalidPrices(); // Need to prepare condition through oracle, because only it can set // initial price/halt time directly if (!addresses.conditionOracle.supportsInterface(ICONDITION_ORACLE_INTERFACE_ID)) { revert InvalidConditionOracle(addresses.conditionOracle); } IConditionOracleV1_2 conditionOracle = IConditionOracleV1_2(addresses.conditionOracle); // prepareCondition is idempotent, so should not fail if already exists ConditionID conditionId = conditionOracle.prepareCondition( addresses.conditionalTokens, params.questionId, outcomeSlotCount, params.packedPrices, params.haltTime ); return _createMarket(fee, addresses, conditionId, params.haltTime); } /// @dev Internal function that assumes condition has already been created function _createMarket( uint256 fee, MarketAddressParams calldata addresses, ConditionID conditionId, uint32 haltTime ) private returns (IMarketMakerV1_2) { // The salt determines the final address of the market clone. One cannot // deploy two clones with the same salt, because they will clash in // their address and the deployment would revert. // // haltTime and fee are missing from the salt, so noone can keep // creating markets with different fees and halt times for the same // questionId. // The reason they are excluded is because they don't create a // fundamentally different identity for a market. If you change the // questionId, it's a market for a different event/bet. If you change // collateralTokens that's a market with a different payment option. // conditionalTokens is where settlement is recorded. priceOracle is who is // the authority to decide the fair prices. haltTime and fee should be // adjustable on the market itself bytes32 salt = marketSalt(addresses, conditionId); MarketMaker.InitParams memory initParams = MarketMaker.InitParams(conditionId, fee); // Check if clone already exists for this salt. If it does, then we have already created and initialized it address clone = Clones.predictDeterministicAddress(marketTemplate, salt); if (clone.isContract()) { return MarketMaker(clone); } address cloneActual = Clones.cloneDeterministic(marketTemplate, salt); assert(cloneActual == clone); // this always has to be true MarketMaker market = MarketMaker(clone); emit MarketMakerCreation( msg.sender, market, addresses.conditionalTokens, addresses.collateralToken, initParams.conditionId, haltTime, initParams.fee ); market.initialize(addresses, initParams); return market; } // TODO: remove? /// @dev Compatibility implementation of old interface without packed prices function createMarket(uint256 fee, MarketAddressParams calldata addresses, PriceMarketParams memory params) public returns (IMarketMakerV1) { if (params.haltTime > type(uint32).max) revert InvalidHaltTime(); PackedPriceMarketParams memory newParams = PackedPriceMarketParams( params.questionId, PackedPrices.toPackedPrices(params.fairPriceDecimals, PackedPrices.DECIMAL_CONVERSION_FACTOR), uint32(params.haltTime) ); return createMarket(fee, addresses, newParams); } /// @notice Same as createMarket, but returns the concrete type /// @dev Need this because of lack of covariant return types: https://github.com/ethereum/solidity/issues/11624 function createMarketConcrete( uint256 fee, MarketAddressParams calldata addresses, PackedPriceMarketParams memory params ) public returns (MarketMaker) { return MarketMaker(address(createMarket(fee, addresses, params))); } function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControlUpgradeable) returns (bool) { return interfaceId == type(IMarketFactory).interfaceId || interfaceId == type(IMarketFactoryV1_2).interfaceId || interfaceId == type(IMarketFactoryV1_3).interfaceId || super.supportsInterface(interfaceId); } // TODO: needs to be idempotent function createParlayMarket( uint256 fee, MarketAddressParams calldata addresses, uint256 legQuestionIdMask, ParlayLegs calldata legs ) public returns (IMarketMakerV1_2 marketMaker, QuestionID parlayQuestionId) { ConditionID parlayConditionId; // TODO check if interface supported? (parlayQuestionId, parlayConditionId) = IParlayConditionalTokens(address(addresses.conditionalTokens)) .prepareParlayCondition(addresses.conditionOracle, legQuestionIdMask, legs); // haltTime isn't explicitly set, since it's derived from the leg halt times. Set it at maximum time in the future. marketMaker = _createMarket(fee, addresses, parlayConditionId, type(uint32).max); } function createParlayMarketConcrete( uint256 fee, MarketAddressParams calldata addresses, uint256 legQuestionIdMask, ParlayLegs calldata legs ) external returns (MarketMaker, QuestionID) { (IMarketMakerV1 marketMaker, QuestionID parlayQuestionId) = createParlayMarket(fee, addresses, legQuestionIdMask, legs); return (MarketMaker(address(marketMaker)), parlayQuestionId); } /// @dev The address of a created market only depends on certain parameters. /// Use this function to determine the final creation address function predictMarketAddress(MarketAddressParams calldata addresses, ConditionID conditionId) public view returns (address) { bytes32 salt = marketSalt(addresses, conditionId); return Clones.predictDeterministicAddress(marketTemplate, salt); } /// @dev Encapsulates how we derive the salt from the creation parameters function marketSalt(MarketAddressParams calldata addresses, ConditionID conditionId) private pure returns (bytes32) { // priceOracle doesn't matter for salt anymore return keccak256( abi.encode( addresses.conditionalTokens, addresses.collateralToken, addresses.parentPool, addresses.conditionOracle, conditionId ) ); } function initialize(address admin, address executor) private initializer { __AdminExecutor_init(admin, executor); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/draft-IERC20Permit.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (proxy/Clones.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes // of the `implementation` address with the bytecode before the address. mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000)) // Packs the remaining 17 bytes of `implementation` with the bytecode after the address. mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3)) instance := create(0, 0x09, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes // of the `implementation` address with the bytecode before the address. mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000)) // Packs the remaining 17 bytes of `implementation` with the bytecode after the address. mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3)) instance := create2(0, 0x09, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) mstore(add(ptr, 0x38), deployer) mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff) mstore(add(ptr, 0x14), implementation) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73) mstore(add(ptr, 0x58), salt) mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37)) predicted := keccak256(add(ptr, 0x43), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.2) (utils/introspection/ERC165Checker.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface. */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return supportsERC165InterfaceUnchecked(account, type(IERC165).interfaceId) && !supportsERC165InterfaceUnchecked(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * * Some precompiled contracts will falsely indicate support for a given interface, so caution * should be exercised when using this function. * * Interface identification is specified in ERC-165. */ function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) { // prepare call bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId); // perform static call bool success; uint256 returnSize; uint256 returnValue; assembly { success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20) returnSize := returndatasize() returnValue := mload(0x00) } return success && returnSize >= 0x20 && returnValue > 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `_msgSender()` is missing `role`. * Overriding this function changes the behavior of the {onlyRole} modifier. * * Format of the revert message is described in {_checkRole}. * * _Available since v4.6._ */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(account), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleGranted} event. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleRevoked} event. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. * * May emit a {RoleRevoked} event. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * May emit a {RoleGranted} event. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. * * May emit a {RoleGranted} event. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. * * May emit a {RoleRevoked} event. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import { IMarketMakerV1 } from "./IMarketMaker.sol"; import { IMarketMakerV1_2 } from "./IMarketMakerV1_2.sol"; import { MarketAddressParams } from "./MarketAddressParams.sol"; import { IConditionalTokens, ConditionID, QuestionID } from "../conditions/IConditionalTokens.sol"; import { ParlayLegs } from "../conditions/IParlayConditionalTokens.sol"; /// @title Events for a market factory /// @dev Use these events for blockchain indexing interface IMarketFactoryEvents { event MarketMakerCreation( address indexed creator, IMarketMakerV1 marketMaker, IConditionalTokens indexed conditionalTokens, IERC20 indexed collateralToken, ConditionID conditionId, uint256 haltTime, uint256 fee ); } interface IMarketFactory is IMarketFactoryEvents, IERC165 { /// @dev Parameters unique to a single Market creation struct PriceMarketParams { QuestionID questionId; uint256[] fairPriceDecimals; uint128 minPriceDecimal; uint256 haltTime; } function createMarket(uint256 fee, MarketAddressParams calldata addresses, PriceMarketParams memory params) external returns (IMarketMakerV1); } interface IMarketFactoryV1_2 is IMarketFactory { /// @dev Parameters unique to a single Market creation, with packed prices struct PackedPriceMarketParams { QuestionID questionId; bytes packedPrices; uint32 haltTime; } function createMarket(uint256 fee, MarketAddressParams calldata addresses, PackedPriceMarketParams memory params) external returns (IMarketMakerV1); } interface IMarketFactoryV1_3 is IMarketFactoryV1_2 { /// @dev create a parlay market out of other conditions. The /// conditionalTokens address is assumed to be an instance of /// ParlayConditionalTokens function createParlayMarket( uint256 fee, MarketAddressParams calldata addresses, uint256 legQuestionIdMask, ParlayLegs calldata legs ) external returns (IMarketMakerV1_2, QuestionID); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import { IERC165Upgradeable } from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import { IERC1155ReceiverUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import { ERC1155ReceiverUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155ReceiverUpgradeable.sol"; import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import { IConditionalTokensV1_2, ConditionID, ConditionalTokensErrors, CTHelpers } from "../conditions/IConditionalTokensV1_2.sol"; import { FundingPool, IFundingPoolV1_1, IFundingPoolV1 } from "../funding/FundingPool.sol"; import { ChildFundingPool, IChildFundingPoolV1, IParentFundingPoolV1 } from "../funding/ChildFundingPool.sol"; import { FeeDistributor, FeeProfileID } from "../funding/FeeDistributor.sol"; import { IMarketMakerV1 } from "./IMarketMaker.sol"; import { IMarketMakerV1_2 } from "./IMarketMakerV1_2.sol"; import { AmmMath } from "./AmmMath.sol"; import { MarketAddressParams } from "./MarketAddressParams.sol"; import { FundingMath } from "../funding/FundingMath.sol"; import { ClampedMath, ArrayMath } from "../Math.sol"; /// @title A contract for providing a market for users to bet on /// @notice A Market for buying, selling bets as a bettor, and adding/removing /// liquidity as a liquidity provider. Any fees acrued due to trading activity /// is then given to the liquidity providers. /// @dev This is using upgradeable contracts because it will be called through a /// proxy. We will not actually be upgrading the proxy, but using proxies for /// cloning. As such, storage compatibilities between upgrades don't matter for /// the Market. contract MarketMaker is Initializable, ERC1155ReceiverUpgradeable, IMarketMakerV1_2, ChildFundingPool, FundingPool, ConditionalTokensErrors { using ArrayMath for uint256[]; using Math for uint256; using ClampedMath for uint256; using SafeERC20 for IERC20Metadata; struct InitParams { ConditionID conditionId; uint256 fee; } uint256 private constant PRECISION_DECIMALS = AmmMath.PRECISION_DECIMALS; uint256 public constant ONE_DECIMAL = AmmMath.ONE_DECIMAL; /// @dev Explicitly ok with immutable state variable as that is set in stone /// in the code deployed, rather than in the storage of every instance of /// the proxy. We are not doing upgrades, so should be ok. /// @custom:oz-upgrades-unsafe-allow state-variable-immutable FeeDistributor private immutable FEE_DISTRIBUTOR; IConditionalTokensV1_2 public conditionalTokens; ConditionID public conditionId; // All decimal values are < 1e18, which can fit in uint64, so can be packed more tightly uint64 public feeDecimal; uint64 public minInvestment; /// @dev Keep track of fees retained by each fee profile. Note that since /// not all profile ids may be approved, any fees for unapproved fee /// profiles just end up given back to the parent pool mapping(FeeProfileID => uint256) private feesByProfile; /// @custom:oz-upgrades-unsafe-allow constructor constructor(FeeDistributor feeDistributor) { // immutable fields get baked into the code, and not storage, so need to // pass these in constructor, not initializer. FEE_DISTRIBUTOR = feeDistributor; _disableInitializers(); } function initialize(MarketAddressParams calldata addresses, InitParams calldata params) public initializer { // Cannot create a market without a parent, because individual funders are forbidden if (addresses.parentPool == address(0x0)) revert NotAParentPool(addresses.parentPool); __ChildFundingPool_init(addresses.parentPool); __FundingPool_init(addresses.collateralToken); __ERC1155Receiver_init(); conditionalTokens = addresses.conditionalTokens; conditionId = params.conditionId; if (isHalted()) revert MarketHalted(); // Check collateral decimals are not too big uint256 collateralDecimals = collateralToken.decimals(); uint256 oneCollateral = 10 ** collateralDecimals; if (oneCollateral >= type(uint64).max) revert ExcessiveCollateralDecimals(); // Check if fee makes sense. It has to be < 1.0 if (params.fee >= oneCollateral) revert InvalidFee(); // Calculate numeric values on the stack and write them out at once after uint256 minInvestment_; if (params.fee > 0) { // Set the minInvestment such that fee will always be non-zero minInvestment_ = oneCollateral.ceilDiv(params.fee); assert(minInvestment_ * params.fee > 0); } else { // if no fee, investment needs to be non-zero minInvestment_ = 1; } // Assert that precision decimals are not excessive. // This is not a requirement, but an assertion because it's a code constant assert(10 ** PRECISION_DECIMALS <= type(uint64).max); // Fee is given in terms of token decimals, but in calculations we use 1 ether precision // We need to normalize the fee to our calculation precision. // Given the above checks, the result should fit within uint64, since it is at most 10 ** PRECISION_DECIMALS uint256 feeDecimal_; if (collateralDecimals < PRECISION_DECIMALS) { feeDecimal_ = params.fee * (10 ** (PRECISION_DECIMALS - collateralDecimals)); } else if (collateralDecimals > PRECISION_DECIMALS) { feeDecimal_ = params.fee / (10 ** (collateralDecimals - PRECISION_DECIMALS)); } else { feeDecimal_ = params.fee; } // Write out adjacent values all at once to take advantage of packing and reducing SSTORE calls feeDecimal = uint64(feeDecimal_); minInvestment = uint64(minInvestment_); { // Ensure they are all stored in the same slot uint256 feeSlot; uint256 minInvestmentSlot; assembly { feeSlot := feeDecimal.slot minInvestmentSlot := minInvestment.slot } assert(feeSlot == minInvestmentSlot); } } /// @inheritdoc IFundingPoolV1 // solhint-disable-next-line ordering function addFunding(uint256 collateralAdded) external returns (uint256 sharesMinted) { return addFundingFor(_msgSender(), collateralAdded); } /// @notice Removes market funds of someone if the condition is resolved. /// All conditional tokens that were part of the position are redeemed and /// only collateral is returned /// @param ownerAndReceiver Address where the collateral will be deposited, /// and who owns the LP tokens /// @param sharesToBurn portion of LP pool to remove function removeCollateralFundingOf(address ownerAndReceiver, uint256 sharesToBurn) public returns (uint256[] memory sendAmounts, uint256 collateralRemoved) { if (!conditionalTokens.isResolved(conditionId)) revert MarketUndecided(); // Fees are distributed first, unless there is a refund, in which case // all the fee collateral will get transferred back to the parent by the // code below (FeeProfileID[] memory profileIds, uint256[] memory profileAmounts, uint256 totalFeeDistributionAmount) = _calcDistributeFees(); // Make any collateral that will not go to the fee distributor part of reserves _unlockFees(collectedFees - totalFeeDistributionAmount); // Remove from reserves (collateralRemoved, sendAmounts) = _calcRemoveFunding(sharesToBurn); _burnSharesOf(ownerAndReceiver, sharesToBurn); uint256 outcomeSlotCount = sendAmounts.length; assert(outcomeSlotCount > 0); uint256[] memory indices = new uint256[](outcomeSlotCount); for (uint256 i = 0; i < outcomeSlotCount; i++) { indices[i] = i; } if (collateralRemoved > 0) { collateralToken.safeTransfer(ownerAndReceiver, collateralRemoved); } collateralRemoved += conditionalTokens.redeemPositionsFor(ownerAndReceiver, collateralToken, conditionId, indices, sendAmounts); _distributeFees(profileIds, profileAmounts, totalFeeDistributionAmount); address parent = getParentPool(); if (ownerAndReceiver == parent) { IParentFundingPoolV1(parent).fundingReturned(collateralRemoved, sharesToBurn); } uint256[] memory noTokens = new uint256[](0); emit FundingRemoved(ownerAndReceiver, collateralRemoved, noTokens, sharesToBurn); } /// @notice Removes all the collateral for funders. Anyone can call /// this function after the condition is resolved. /// @return totalSharesBurnt Total amount of shares that were burnt. /// @return totalCollateralRemoved Total amount of collateral removed. function removeAllCollateralFunding(address[] calldata funders) external returns (uint256 totalSharesBurnt, uint256 totalCollateralRemoved) { for (uint256 i = 0; i < funders.length; i++) { address funder = funders[i]; uint256 sharesToBurn_ = balanceOf(funder); if (sharesToBurn_ == 0) continue; (, uint256 collateralRemoved_) = removeCollateralFundingOf(funder, sharesToBurn_); totalCollateralRemoved += collateralRemoved_; totalSharesBurnt += sharesToBurn_; } } /// @notice Removes funds from the market by burning the shares and sending /// to the transaction sender his portion of conditional tokens and collateral. /// @param sharesToBurn portion of LP pool to remove /// @return collateral how much collateral was returned /// @return sendAmounts how much of each conditional token was returned function removeFunding(uint256 sharesToBurn) external returns (uint256 collateral, uint256[] memory sendAmounts) { address funder = _msgSender(); return _removeFunding(funder, sharesToBurn); } function _removeFunding(address funder, uint256 sharesToBurn) private returns (uint256 collateral, uint256[] memory sendAmounts) { (collateral, sendAmounts) = _calcRemoveFunding(sharesToBurn); _burnSharesOf(funder, sharesToBurn); collateralToken.safeTransfer(funder, collateral); uint256 outcomeSlotCount = sendAmounts.length; conditionalTokens.safeBatchTransferFrom( address(this), funder, CTHelpers.getPositionIds(collateralToken, conditionId, outcomeSlotCount), sendAmounts, "" ); address parent = getParentPool(); if (funder == parent) { IParentFundingPoolV1(parent).fundingReturned(collateral, sharesToBurn); } emit FundingRemoved(funder, collateral, sendAmounts, sharesToBurn); } function _calcRemoveFunding(uint256 sharesToBurn) private view returns (uint256 collateral, uint256[] memory returnAmounts) { uint256 totalShares = totalSupply(); collateral = FundingMath.calcReturnAmount(sharesToBurn, totalShares, reserves()); returnAmounts = FundingMath.calcReturnAmounts(sharesToBurn, totalShares, getPoolBalances()); } function _afterTokenTransfer(address from, address to, uint256 amount) internal override { // When address other than parent gets shares, immediately eject them to // maintain invariant that all funding is by parent if (from == getParentPool() && to != address(0x0)) { _removeFunding(to, amount); } } /// @notice Buys an amount of a conditional token position. /// @param investmentAmount Amount of collateral to exchange for the collateral tokens. /// @param outcomeIndex Position index of the condition to buy. /// @param minOutcomeTokensToBuy Minimal amount of conditional token expected to be received. function buy(uint256 investmentAmount, uint256 outcomeIndex, uint256 minOutcomeTokensToBuy) external returns (uint256 outcomeTokensBought, uint256 feeAmount, uint256[] memory spontaneousPrices) { return buyFor(_msgSender(), investmentAmount, outcomeIndex, minOutcomeTokensToBuy, 0, FeeProfileID.wrap(0x0)); } /// @notice Sells an amount of conditional tokens and get collateral as a /// return. Currently not supported and will be implemented soon. function sell(uint256 returnAmount, uint256, /* outcomeIndex */ uint256 /* maxOutcomeTokensToSell */ ) external view returns (uint256) { if (isHalted()) revert MarketHalted(); if (returnAmount == 0) revert InvalidReturnAmount(); revert OperationNotSupported(); } /// @notice Price updates have moved to Conditional Tokens. function updateFairPrices(uint256[] calldata /* fairPriceDecimals */ ) external pure { revert OperationNotSupported(); } /// @notice Deprecated because refund outcome always has price of 0 function updateMinPrice(uint128 /* _minPriceDecimal */ ) external pure { revert OperationNotSupported(); } /// @notice Return the current fair prices used by the market, normalized to ONE_DECIMAL function getFairPrices() external view returns (uint256[] memory) { return conditionalTokens.getFairPrices(conditionId); } /// @notice Return the current prices that include the spread due to the AMM /// algorithm. The prices will sum to more than ONE_DECIMAL, because there /// is a spread incorporated into the price function getSpontaneousPrices() external view returns (uint256[] memory) { (AmmMath.TargetContext memory targetContext, uint256[] memory fairPriceDecimals) = getTargetBalance(); return AmmMath.calcSpontaneousPricesV3( targetContext.target, targetContext.globalReserves, targetContext.balances, fairPriceDecimals ); } function getPoolValue() public view returns (uint256) { (uint256[] memory poolBalances, uint256[] memory fairPriceDecimals) = conditionalTokens.getPositionInfo(address(this), collateralToken, conditionId); return AmmMath.calcPoolValue(poolBalances, fairPriceDecimals, reserves()); } /// @inheritdoc IFundingPoolV1 function addFundingFor(address receiver, uint256 collateralAdded) public returns (uint256 sharesMinted) { if (isHalted()) revert MarketHalted(); if (receiver != getParentPool()) revert CanOnlyBeFundedByParent(); sharesMinted = _mintSharesFor(receiver, collateralAdded, getPoolValue()); // Don't split through all conditions, keep collateral as collateral, until we actually need it } /// @notice Buys conditional tokens for a particular account. /// @dev This function is to buy conditional tokens by a third party on behalf of a particular account. /// @param outcomeIndex Position index of the condition to buy. /// @param minOutcomeTokensToBuy Minimal amount of conditional token expected to be received. /// @return outcomeTokensBought quantity of conditional tokens that were bought /// @return feeAmount how much collateral went to fees function buyFor(address receiver, uint256 investmentAmount, uint256 outcomeIndex, uint256 minOutcomeTokensToBuy) external returns (uint256 outcomeTokensBought, uint256 feeAmount, uint256[] memory spontaneousPrices) { return buyFor(receiver, investmentAmount, outcomeIndex, minOutcomeTokensToBuy, 0, FeeProfileID.wrap(0x0)); } function buyFor( address receiver, uint256 investmentAmount, uint256 outcomeIndex, uint256 minOutcomeTokensToBuy, uint256 extraFeeDecimal, FeeProfileID feeProfileId ) public returns (uint256 outcomeTokensBought, uint256 feeAmount, uint256[] memory spontaneousPrices) { if (isHalted()) revert MarketHalted(); if (investmentAmount < minInvestment) revert InvalidInvestmentAmount(); uint256 tokensToMint; uint256 refundIndex; AmmMath.ParentOperations memory parentOps; { (AmmMath.TargetContext memory targetContext, uint256[] memory fairPriceDecimals) = getTargetBalance(); refundIndex = AmmMath.getRefundIndex(targetContext); (outcomeTokensBought, tokensToMint, feeAmount, spontaneousPrices, parentOps) = _calcBuyAmount(investmentAmount, outcomeIndex, extraFeeDecimal, targetContext, fairPriceDecimals); } if (outcomeTokensBought < minOutcomeTokensToBuy) revert MinimumBuyAmountNotReached(); // Request from parent first, before receiving any collateral from the // buyer, otherwise the extra collateral from the buyer skews the pool // value. This skew is wrong because that extra collateral will be used // to mint conditional tokens and be given away. _applyParentRequest(parentOps); collateralToken.safeTransferFrom(_msgSender(), address(this), investmentAmount); // Should set aside the fee collateral. In case of a refund outcome, all of the fee // goes back to LP because LP provided the collateral for the refund in // the first place _retainFees(feeAmount, feeProfileId); if (tokensToMint > 0) { // We need to mint some tokens splitPositionThroughAllConditions(tokensToMint); } conditionalTokens.safeTransferFrom(address(this), receiver, positionId(outcomeIndex), outcomeTokensBought, ""); // Last index outcome is the refund outcome. Give back the same amount of tokens as collateral invested, including fees conditionalTokens.safeTransferFrom(address(this), receiver, positionId(refundIndex), investmentAmount, ""); // Return collateral back to parent once everything is settled with the buyer _applyParentReturn(parentOps); emit MarketBuy(receiver, investmentAmount, feeAmount, outcomeIndex, outcomeTokensBought); emit MarketSpontaneousPrices(spontaneousPrices); } /// @inheritdoc IERC1155ReceiverUpgradeable function onERC1155Received( address operator, address, /* from */ uint256, /* id */ uint256, /* value */ bytes memory /* data */ ) public view override returns (bytes4) { // receives conditional tokens for the liquidity pool, // or transfer from a user for purpose of selling that token if (operator == address(this) && _msgSender() == address(conditionalTokens)) { return this.onERC1155Received.selector; } return 0x0; } /// @inheritdoc IERC1155ReceiverUpgradeable function onERC1155BatchReceived( address operator, address from, uint256[] memory, /* ids */ uint256[] memory, /* values */ bytes memory /* data */ ) public view override returns (bytes4) { // receives conditional tokens for the liquidity pool from splitPositions if (operator == address(this) && from == address(0) && _msgSender() == address(conditionalTokens)) { return this.onERC1155BatchReceived.selector; } return 0x0; } /// @dev Convenience view function to calculate a positionId (ERC1155 id) for an outcome function positionId(uint256 outcomeIndex) public view returns (uint256) { return CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(conditionId, outcomeIndex)); } /// @notice Calculate the amount of conditional token to be bought with a certain amount of collateral. /// @param investmentAmount Amount of collateral token invested. /// @param indexOut Position index of the condition. /// @return outcomeTokensBought how many outcome tokens would the user receive from the transaction function calcBuyAmount(uint256 investmentAmount, uint256 indexOut) external view returns (uint256, uint256, uint256[] memory) { return calcBuyAmount(investmentAmount, indexOut, 0); } function calcBuyAmount(uint256 investmentAmount, uint256 indexOut, uint256 extraFeeDecimal) public view returns (uint256 outcomeTokensBought, uint256 feeAmount, uint256[] memory spontaneousPrices) { (AmmMath.TargetContext memory targetContext, uint256[] memory fairPriceDecimals) = getTargetBalance(); (outcomeTokensBought,, feeAmount, spontaneousPrices,) = _calcBuyAmount(investmentAmount, indexOut, extraFeeDecimal, targetContext, fairPriceDecimals); } /// @dev Calculate the amount of a conditional token to be bought with a /// certain amount of collateral. This private function also provides a lot /// of other information on how to deal with an external parent pool. /// /// Some invariants: /// - No collateral stays in the market - reserves should be 0. The minimal /// amount of collateral is requested from the parent in order to mint /// tokens. Any excess after all operations is given back to the parent /// - At the end of a buy operation at least one of the token balances is 0, /// otherwise some amount would be mergeable. The market remains without /// collateral reserves, and with some tokens besides the output token. If /// a subsequent buy takes some tokens that are readily available, that /// allows us to return the investment collateral of the buyer back to the /// parent pool, since we don't need it to mint any tokens. /// - This means the parent pool's effective funding is ALWAYS in terms of /// tokens in the market, because any excess collateral is always returned /// back to the parent /// - The AMM algorithm aims to keep the pool value constant, and all the /// balances to be at a target. This target is the cost basis of all /// funding. The idea is all revenue comes from a flat fee on trades, and /// the funding pool itself tries to keep a steady value. /// - Sometimes a bet results in a "push" requiring a full refund. This /// necessitates setting aside an outcome for a full refund. Tokens of this /// extra outcome are worth zero during normal trading, and are given out /// 1:1 for every collateral the user puts in. This has to be taken into /// account when calculating how much to request from the parent, since we /// also need to mint enough tokens to fulfill the refund obligation /// @param investment Amount of collateral token used to buy tokens /// @param indexOut Position index of the condition. /// @param extraFeeDecimal extra fees as a decimal to add on top of existing fees /// @param targetContext the current state of the pool - target, balances, available liquidity /// @param fairPriceDecimals current fair prices for all priced outcomes /// @return outcomeTokensBought how many outcome tokens would the user receive from the transaction /// @return tokensToMint the minimal number of tokens to mint in order to satisfy the order /// @return fees how much collateral is taken as fees /// @return spontaneousPrices pries of tokens after the buy /// @return parentOps operations to perform with parent funding function _calcBuyAmount( uint256 investment, uint256 indexOut, uint256 extraFeeDecimal, AmmMath.TargetContext memory targetContext, uint256[] memory fairPriceDecimals ) private view returns ( uint256 outcomeTokensBought, uint256 tokensToMint, uint256 fees, uint256[] memory spontaneousPrices, AmmMath.ParentOperations memory parentOps ) { fees = (investment * (feeDecimal + extraFeeDecimal)) / ONE_DECIMAL; if (fees >= investment) revert FeesConsumeInvestment(); uint256 investmentMinusFees = investment - fees; (uint256 tokensExchanged, uint256 newPoolValue) = AmmMath.calcBuyAmountV3( investmentMinusFees, indexOut, targetContext.target, targetContext.globalReserves, targetContext.balances, fairPriceDecimals ); AmmMath.BuyContext memory buyContext = AmmMath.BuyContext(investmentMinusFees, tokensExchanged, newPoolValue, investment); address parent = getParentPool(); uint256 parentShares = balanceOf(parent); assert(parentShares == totalSupply()); // All shares should be owned by parent (outcomeTokensBought, tokensToMint, parentOps) = AmmMath.calcMarketPoolChanges(indexOut, parentShares, targetContext, buyContext); spontaneousPrices = AmmMath.calcSpontaneousPricesV3( targetContext.target, targetContext.globalReserves, targetContext.balances, fairPriceDecimals ); } /// @notice Calculates the amount of conditional tokens that should be sold to receive a particular amount of /// collateral. Currently not supported but will be implemented soon function calcSellAmount(uint256, /* returnAmount */ uint256 /* outcomeIndex */ ) public pure returns (uint256) { revert OperationNotSupported(); } /// ERC165 /// @dev This should check all incremental interfaces. Reasoning: /// - Market shows support for all revisions of the interface up to latest. /// - BatchBet checks the minimal version that supports the function it needs. /// - Any other contract also only checks the minimal version that supports the function it needs. /// - When a new interface is released, there is no need to release new versions of "user" contracts like /// BatchBet, because they use the minimal interface and new releases of markets will be backwards compatible. function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC1155ReceiverUpgradeable) returns (bool) { return interfaceId == type(IMarketMakerV1).interfaceId || interfaceId == type(IChildFundingPoolV1).interfaceId || interfaceId == type(IFundingPoolV1).interfaceId || interfaceId == type(IFundingPoolV1_1).interfaceId || interfaceId == type(IMarketMakerV1_2).interfaceId || ERC1155ReceiverUpgradeable.supportsInterface(interfaceId); } /// @notice Returns true/false if the market is currently halted or not, respectively. /// @dev It would be more convenient to use block number since the timestamp is modifiable by miners function isHalted() public view returns (bool) { return conditionalTokens.isHalted(conditionId); } /// @notice Computes the pool balance in conditional token for each market position. /// @return poolBalances The pool balance in conditional tokens for each position. function getPoolBalances() public view returns (uint256[] memory) { return conditionalTokens.balanceOfCondition(address(this), collateralToken, conditionId); } /// @dev It would be maybe convenient to remove this function since it is used only once in the code and adds extra /// complexity. If it names clarifies better what splitPosition those it could be just changed in the /// ConditionalContract function splitPositionThroughAllConditions(uint256 amount) private { collateralToken.safeApprove(address(conditionalTokens), amount); conditionalTokens.splitPosition(collateralToken, conditionId, amount); } /// @dev Requests funds from parent if needed function _applyParentRequest(AmmMath.ParentOperations memory parentOps) private { address parent = getParentPool(); if (parentOps.collateralToRequestFromParent > 0) { assert(parentOps.collateralToReturnToParent == 0); assert(parentOps.sharesToBurnOfParent == 0); // We need more collateral than available in reserves, so ask the parent assert(parent != address(0x0)); (uint256 fundingGiven,) = IParentFundingPoolV1(parent).requestFunding(parentOps.collateralToRequestFromParent); if (fundingGiven < parentOps.collateralToRequestFromParent) revert InvestmentDrainsPool(); } } /// @dev Returns funds back to parent if available function _applyParentReturn(AmmMath.ParentOperations memory parentOps) private { address parent = getParentPool(); if (parentOps.sharesToBurnOfParent > 0 || parentOps.collateralToReturnToParent > 0) { assert(parentOps.collateralToRequestFromParent == 0); // We have extra collateral that should be returned back to the parent assert(parent != address(0x0)); if (parentOps.sharesToBurnOfParent > 0) { _burnSharesOf(parent, parentOps.sharesToBurnOfParent); } if (parentOps.collateralToReturnToParent > 0) { collateralToken.safeTransfer(parent, parentOps.collateralToReturnToParent); } IParentFundingPoolV1(parent).fundingReturned( parentOps.collateralToReturnToParent, parentOps.sharesToBurnOfParent ); uint256[] memory noTokens = new uint256[](0); emit FundingRemoved(parent, parentOps.collateralToReturnToParent, noTokens, parentOps.sharesToBurnOfParent); } } /// @dev calculates how the fees should be distributed. Calculation is split from action to avoid re-entrancy attacks function _calcDistributeFees() private view returns (FeeProfileID[] memory profileIds, uint256[] memory profileAmounts, uint256 totalAmount) { uint256 collectedFees_ = collectedFees; if (collectedFees_ == 0) return (profileIds, profileAmounts, totalAmount); // If there is a refund, all fees go back to parent since it funded the // refunds in the first place. No distribution to others takes place (uint256[] memory numerators,) = conditionalTokens.getPayouts(conditionId); uint256 refundIndex = AmmMath.getRefundIndex(numerators); if (numerators[refundIndex] > 0) return (profileIds, profileAmounts, totalAmount); // Send to fee distributor profileIds = FEE_DISTRIBUTOR.approvedProfiles(); profileAmounts = new uint256[](profileIds.length); totalAmount = 0; for (uint256 i = 0; i < profileIds.length; i++) { FeeProfileID profileId = profileIds[i]; uint256 profileFees = feesByProfile[profileId]; if (profileFees == 0) continue; profileAmounts[i] = profileFees; totalAmount += profileFees; } } function _distributeFees(FeeProfileID[] memory profileIds, uint256[] memory profileAmounts, uint256 totalAmount) private { if (totalAmount == 0) return; // Make fees part of reserves _unlockFees(totalAmount); collateralToken.approve(address(FEE_DISTRIBUTOR), totalAmount); FEE_DISTRIBUTOR.transferToProfiles(collateralToken, profileIds, profileAmounts); } function _retainFees(uint256 feeAmount, FeeProfileID feeProfileId) private { _retainFees(feeAmount); if (FeeProfileID.unwrap(feeProfileId) != 0x0) { feesByProfile[feeProfileId] += feeAmount; } } /// @dev Gets the actual target balance available, that includes any /// potential funding from the parent pool. /// @return targetContext relevant quantities needed to work with the liquidity pool function getTargetBalance() public view returns (AmmMath.TargetContext memory targetContext, uint256[] memory fairPriceDecimals) { // The logic is such that any excess collateral is always returned to the parent // We don't use reserves() here as that may be altered by donations to the market uint256[] memory balances; (balances, fairPriceDecimals) = conditionalTokens.getPositionInfo(address(this), collateralToken, conditionId); // Ensure last price is for refund outcome and price is 0 assert(balances.length == fairPriceDecimals.length + 1); targetContext = AmmMath.TargetContext({ target: getTotalFunderCostBasis(), globalReserves: 0, balances: balances }); // check how much funding we can actually request from parent address parent = getParentPool(); if (parent != address(0x0)) { (uint256 availableFromParent, uint256 availableTarget) = IParentFundingPoolV1(parent).getAvailableFunding(address(this)); targetContext.target += availableTarget; targetContext.globalReserves += availableFromParent; } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { AmmErrors } from "./AmmErrors.sol"; import { FundingErrors } from "../funding/FundingErrors.sol"; interface MarketErrors is AmmErrors, FundingErrors { error MarketHalted(); error MarketUndecided(); // Buy error InvalidInvestmentAmount(); error MinimumBuyAmountNotReached(); error FeesConsumeInvestment(); // Sell error InvalidReturnAmount(); error MaximumSellAmountExceeded(); error InvestmentDrainsPool(); error OperationNotSupported(); error CanOnlyBeFundedByParent(); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IConditionalTokensEvents, IConditionalTokens, IERC20, ConditionalTokensErrors } from "./IConditionalTokens.sol"; import { PackedPrices } from "../PackedPrices.sol"; import { ConditionID, QuestionID, CTHelpers } from "./CTHelpers.sol"; interface IConditionalTokensEventsV1_2 is IConditionalTokensEvents { /// @dev Event emitted only when a condition is prepared to save on gas costs /// @param conditionId which condition had its price set /// @param packedPrices the encoded prices in a byte array event ConditionPricesUpdated(ConditionID indexed conditionId, bytes packedPrices); /// @dev Halt time for a condition has been updated event HaltTimeUpdated(ConditionID indexed conditionId, uint32 haltTime); } interface IConditionalTokensV1_2 is IConditionalTokens, IConditionalTokensEventsV1_2 { struct PriceUpdate { ConditionID conditionId; bytes packedPrices; } struct HaltUpdate { ConditionID conditionId; /// @dev haltTime as seconds since epoch, same as block.timestamp /// unsigned 32bit epoch timestamp in seconds should be suitable until year 2106 uint32 haltTime; } function prepareConditionByOracle( QuestionID questionId, uint256 outcomeSlotCount, bytes calldata packedPrices, uint32 haltTime_ ) external returns (ConditionID); function updateFairPrices(ConditionID conditionId, bytes calldata packedPrices) external; function batchUpdateFairPrices(PriceUpdate[] calldata priceUpdates) external; function getFairPrices(ConditionID conditionId) external view returns (uint256[] memory fairPriceDecimals); function updateHaltTime(ConditionID conditionId, uint32 haltTime) external; function batchUpdateHaltTimes(HaltUpdate[] calldata haltUpdates) external; /// @dev Returns the halt time of a condition. Will be 0 if no price oracle /// is configured (if old prepareCondition was called). function haltTime(ConditionID conditionId) external view returns (uint32); /// @dev Returns if the condition is halted or already resolved. Halting /// only effects price updates. If no price oracle was configured for a /// condition, this will always return true. This is ok since it does not /// affect any other aspect. function isHalted(ConditionID conditionId) external view returns (bool); /// @dev combines together balanceOfCondition and getFairPrices into one call to minimize gas usage function getPositionInfo(address account, IERC20 collateralToken, ConditionID conditionId) external view returns (uint256[] memory balances, uint256[] memory fairPriceDecimals); /// @dev Get the current payouts for a condition. function getPayouts(ConditionID conditionId) external view returns (uint256[] memory numerators, uint256 denominator); } interface ILegConditionalTokens { /// @dev given conditions and indices within those conditions, gives the fair price for the parlay function getParlayFairPrices(ConditionID[] calldata conditionIds, uint256[] calldata indices) external view returns (uint256[] memory fairPriceDecimals); /// @dev given conditions and indices within those conditions, gives the payout for the parlay function getParlayPayouts(ConditionID[] calldata conditionIds, uint256[] calldata indices) external view returns (uint256[] memory numerators, uint256 denominator); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IConditionalTokens, IConditionalTokensV1_2, QuestionID, ConditionID } from "./IConditionalTokensV1_2.sol"; interface IConditionOracleV1_2 { function batchReportPayouts( IConditionalTokens conditionalTokens, QuestionID[] calldata questionIDs, uint256[] calldata payouts, uint256[] calldata outcomeSlotCounts ) external; function batchUpdateHaltTimes( IConditionalTokensV1_2 conditionalTokens, IConditionalTokensV1_2.HaltUpdate[] calldata haltUpdates ) external; function batchUpdatePackedPrices( IConditionalTokensV1_2 condTokens, IConditionalTokensV1_2.PriceUpdate[] calldata priceUpdates ) external; function prepareCondition( IConditionalTokensV1_2 condTokens, QuestionID questionId, uint256 outcomeSlotCount, bytes calldata packedPrices, uint32 haltTime ) external returns (ConditionID); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; /// @dev Simple Access Control, that has an admin role that administers an /// executor role. The intent is to have a multi-sig or other mechanism to be /// the admin, and be able to grant/revoke accounts as executors. abstract contract AdminExecutorAccessUpgradeable is AccessControlUpgradeable, PausableUpgradeable { bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); modifier onlyAdmin() { checkAdmin(_msgSender()); _; } modifier onlyExecutor() { checkExecutor(_msgSender()); _; } // solhint-disable-next-line func-name-mixedcase function __AdminExecutor_init(address admin, address startingExecutor) internal onlyInitializing { __AccessControl_init(); __Pausable_init(); __AdminExecutor_init_unchained(admin, startingExecutor); } // solhint-disable-next-line func-name-mixedcase function __AdminExecutor_init_unchained(address admin, address startingExecutor) internal onlyInitializing { _grantRole(DEFAULT_ADMIN_ROLE, admin); // DEFAULT_ADMIN_ROLE already is admin for executor by default, so no need for _setRoleAdmin if (startingExecutor != address(0x0)) { _grantRole(EXECUTOR_ROLE, startingExecutor); } } function pause() public onlyAdmin { _pause(); } function unpause() public onlyAdmin { _unpause(); } /// @dev Check is a particular account has executor permissions. Reverts if not the case. /// @param account the account to check function checkExecutor(address account) public view { _checkRole(EXECUTOR_ROLE, account); } function checkAdmin(address account) public view { _checkRole(DEFAULT_ADMIN_ROLE, account); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { ConditionID, QuestionID } from "./CTHelpers.sol"; struct ParlayLegs { /// @dev list of unique questionIds to be used as legs in the parlay QuestionID[] questionIds; /// @dev the outcome index in each leg of the parlay uint256[] indices; /// @dev number of outcomes for each questionId. Needed to reconstruct the conditionIds uint256[] outcomeSlotCounts; } interface IParlayConditionalTokensEvents { event ParlayConditionLegs( ConditionID indexed conditionId, QuestionID indexed questionId, address indexed legOracle, uint256 legQuestionIdMask, ParlayLegs legs ); } interface IParlayConditionalTokens { /// @dev Prepare a condition that is a parlay of several other conditions as legs of the parlay. /// @param legOracle the condition oracle providing resolutions for all the conditions in the parlay /// @param legQuestionIdMask When considering uniqueness and ordering, this /// bitmask will be applied to the questionId. This can be used to restrict /// parlays to only be possible across different events. /// @param legs list of all legs /// @return parlayQuestionId the synthetic questionID of the parlay /// @return parlayConditionId the conditionId of the parlay function prepareParlayCondition(address legOracle, uint256 legQuestionIdMask, ParlayLegs calldata legs) external returns (QuestionID parlayQuestionId, ConditionID parlayConditionId); /// @dev report parlay payouts for a questionId in a permissionless manner. /// The payout is deterministically decided by the payouts of the legs of the parlay. /// If not all leg conditions are resolved, will revert. /// If parlay condition is already resolved, will do nothing (idempotent) /// @param parlayQuestionId the parlay id (returned when creating the parlay condition) function reportParlayPayouts(QuestionID parlayQuestionId) external; function batchReportParlayPayouts(QuestionID[] calldata parlayQuestionIds) external; /// @dev Calculates the derived Parlay QuestionID from underlying conditional token leg conditions /// @param legOracle the oracle address used for all the underlying legs /// @param legQuestionIds all the leg questionIds /// @param legQuestionIdMask When considering uniqueness and ordering, this /// bitmask will be applied to the questionId. This can be used to restrict /// parlays to only be possible across different events. /// @param legIndices the outcome index in each leg of the parlay /// @return parlayQuestionId the derived QuestionID for the parlay function getParlayQuestionId( address legOracle, QuestionID[] calldata legQuestionIds, uint256 legQuestionIdMask, uint256[] calldata legIndices ) external pure returns (QuestionID); function getParlayConditionId(QuestionID parlayQuestionId) external pure returns (ConditionID); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; // Note on libraries. If any functions are not `internal`, then contracts that // use the libraries, must be linked. library ArrayMath { function sum(uint256[] memory values) internal pure returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < values.length; i++) { result += values[i]; } return result; } } /// @dev Math with saturation/clamping for overflow/underflow handling library ClampedMath { /// @dev min(upper, max(lower, x)) function clampBetween(uint256 x, uint256 lower, uint256 upper) internal pure returns (uint256) { unchecked { return x < lower ? lower : (x > upper ? upper : x); } } /// @dev max(0, a - b) function subClamp(uint256 a, uint256 b) internal pure returns (uint256) { unchecked { return a > b ? a - b : 0; } } /// @dev min(type(uint256).max, max(0, a + b)) function addClamp(uint256 a, int256 b) internal pure returns (uint256) { unchecked { if (b < 0) { // The absolute value of type(int256).min is not representable // in int256, so have to dance about with the + 1 uint256 positiveB = uint256(-(b + 1)) + 1; return (a > positiveB) ? (a - positiveB) : 0; } else { return type(uint256).max - a > uint256(b) ? a + uint256(b) : type(uint256).max; } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol) pragma solidity ^0.8.0; import "./math/MathUpgradeable.sol"; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = MathUpgradeable.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, MathUpgradeable.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ``` * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a * constructor. * * Emits an {Initialized} event. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: setting the version to 255 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized < type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _initializing; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { MarketErrors } from "./MarketErrors.sol"; import { IFundingPoolV1 } from "../funding/IFundingPoolV1.sol"; import { IUpdateFairPrices } from "./IUpdateFairPrices.sol"; /// @dev Interface evolution is done by creating new versions of the interfaces /// and making sure that the derived MarketMaker supports all of them. /// Alternatively we could have gone with breaking the interface down into each /// function one by one and checking each function selector. This would /// introduce a lot more code in `supportsInterface` which is called often, so /// it's easier to keep track of incremental evolution than all the constituent /// pieces interface IMarketMakerV1 is IFundingPoolV1, IUpdateFairPrices, MarketErrors { event MarketBuy( address indexed buyer, uint256 investmentAmount, uint256 feeAmount, uint256 indexed outcomeIndex, uint256 outcomeTokensBought ); event MarketSell( address indexed seller, uint256 returnAmount, uint256 feeAmount, uint256 indexed outcomeIndex, uint256 outcomeTokensSold ); event MarketSpontaneousPrices(uint256[] spontaneousPrices); function removeFunding(uint256 sharesToBurn) external returns (uint256 collateral, uint256[] memory sendAmounts); function buyFor(address receiver, uint256 investmentAmount, uint256 outcomeIndex, uint256 minOutcomeTokensToBuy) external returns (uint256 outcomeTokensBought, uint256 feeAmount, uint256[] memory spontaneousPrices); function buy(uint256 investmentAmount, uint256 outcomeIndex, uint256 minOutcomeTokensToBuy) external returns (uint256 outcomeTokensBought, uint256 feeAmount, uint256[] memory spontaneousPrices); function sell(uint256 returnAmount, uint256 outcomeIndex, uint256 maxOutcomeTokensToSell) external returns (uint256 outcomeTokensSold); function removeCollateralFundingOf(address ownerAndReceiver, uint256 sharesToBurn) external returns (uint256[] memory sendAmounts, uint256 collateral); function removeAllCollateralFunding(address[] calldata funders) external returns (uint256 totalSharesBurnt, uint256 totalCollateralRemoved); function isHalted() external view returns (bool); function calcBuyAmount(uint256 investmentAmount, uint256 outcomeIndex) external view returns (uint256 outcomeTokensBought, uint256 feeAmount, uint256[] memory spontaneousPrices); function calcSellAmount(uint256 returnAmount, uint256 outcomeIndex) external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IMarketMakerV1 } from "./IMarketMaker.sol"; import { FeeProfileID } from "../funding/FeeDistributor.sol"; interface IMarketMakerV1_2 is IMarketMakerV1 { /// @dev Same as the simpler buyFor, except using a custom feeProfile for how to distribute the fees /// @param receiver Which account receives te bought conditional tokens /// @param investmentAmount How much collateral to spend on the order /// @param outcomeIndex Which outcome to purchase /// @param minOutcomeTokensToBuy Minimal amount of conditional tokens expected to be received. Controls max slippage /// @param extraFeeDecimal If buyer wants to deposit any extra fees on top of the ones set by the market /// @param feeProfileId Fee Profile Id determines how overall fees are ultimately distributed to beneficiaries function buyFor( address receiver, uint256 investmentAmount, uint256 outcomeIndex, uint256 minOutcomeTokensToBuy, uint256 extraFeeDecimal, FeeProfileID feeProfileId ) external returns (uint256 outcomeTokensBought, uint256 feeAmount, uint256[] memory spontaneousPrices); function calcBuyAmount(uint256 investmentAmount, uint256 indexOut, uint256 extraFeeDecimal) external view returns (uint256 outcomeTokensBought, uint256 feeAmount, uint256[] memory spontaneousPrices); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IConditionalTokensV1_2 } from "../conditions/IConditionalTokensV1_2.sol"; import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; struct MarketAddressParams { IConditionalTokensV1_2 conditionalTokens; IERC20Metadata collateralToken; address parentPool; address priceOracle; address conditionOracle; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC1155Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import { ConditionID, QuestionID } from "./CTHelpers.sol"; import { ConditionalTokensErrors } from "./ConditionalTokensErrors.sol"; /// @title Events emitted by conditional tokens /// @dev Minimal interface to be used for blockchain indexing (e.g subgraph) interface IConditionalTokensEvents { /// @dev Emitted upon the successful preparation of a condition. /// @param conditionId The condition's ID. This ID may be derived from the /// other three parameters via ``keccak256(abi.encodePacked(oracle, /// questionId, outcomeSlotCount))``. /// @param oracle The account assigned to report the result for the prepared condition. /// @param questionId An identifier for the question to be answered by the oracle. /// @param outcomeSlotCount The number of outcome slots which should be used /// for this condition. Must not exceed 256. event ConditionPreparation( ConditionID indexed conditionId, address indexed oracle, QuestionID indexed questionId, uint256 outcomeSlotCount ); event ConditionResolution( ConditionID indexed conditionId, address indexed oracle, QuestionID indexed questionId, uint256 outcomeSlotCount, uint256[] payoutNumerators ); /// @dev Emitted when a position is successfully split. event PositionSplit( address indexed stakeholder, IERC20 collateralToken, ConditionID indexed conditionId, uint256 amount ); /// @dev Emitted when positions are successfully merged. event PositionsMerge( address indexed stakeholder, IERC20 collateralToken, ConditionID indexed conditionId, uint256 amount ); /// @notice Emitted when a subset of outcomes are redeemed for a condition event PayoutRedemption( address indexed redeemer, IERC20 indexed collateralToken, ConditionID conditionId, uint256[] indices, uint256 payout ); } interface IConditionalTokens is IERC1155Upgradeable, IConditionalTokensEvents, ConditionalTokensErrors { function prepareCondition(address oracle, QuestionID questionId, uint256 outcomeSlotCount) external returns (ConditionID); function reportPayouts(QuestionID questionId, uint256[] calldata payouts) external; function batchReportPayouts( QuestionID[] calldata questionIDs, uint256[] calldata payouts, uint256[] calldata outcomeSlotCounts ) external; function splitPosition(IERC20 collateralToken, ConditionID conditionId, uint256 amount) external; function mergePositions(IERC20 collateralToken, ConditionID conditionId, uint256 amount) external; function redeemPositionsFor( address receiver, IERC20 collateralToken, ConditionID conditionId, uint256[] calldata indices, uint256[] calldata quantities ) external returns (uint256); function redeemAll(IERC20 collateralToken, ConditionID[] calldata conditionIds, uint256[] calldata indices) external; function redeemAllOf( address ownerAndReceiver, IERC20 collateralToken, ConditionID[] calldata conditionIds, uint256[] calldata indices ) external returns (uint256 totalPayout); function balanceOfCondition(address account, IERC20 collateralToken, ConditionID conditionId) external view returns (uint256[] memory); function isResolved(ConditionID conditionId) external view returns (bool); function getPositionIds(IERC20 collateralToken, ConditionID conditionId) external view returns (uint256[] memory); // TODO: This should be ok to add to the first interface, since we currently don't use the interface id directly anywhere, // and the very first version of the contract did support this function. /// @dev number of outcome slots in a condition function getOutcomeSlotCount(ConditionID conditionId) external view returns (uint256); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol) pragma solidity ^0.8.0; import "../IERC1155ReceiverUpgradeable.sol"; import "../../../utils/introspection/ERC165Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155ReceiverUpgradeable is Initializable, ERC165Upgradeable, IERC1155ReceiverUpgradeable { function __ERC1155Receiver_init() internal onlyInitializing { } function __ERC1155Receiver_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^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 { 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) { return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^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; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv( uint256 x, uint256 y, uint256 denominator, Rounding rounding ) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // 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 + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10**64) { value /= 10**64; result += 64; } if (value >= 10**32) { value /= 10**32; result += 32; } if (value >= 10**16) { value /= 10**16; result += 16; } if (value >= 10**8) { value /= 10**8; result += 8; } if (value >= 10**4) { value /= 10**4; result += 4; } if (value >= 10**2) { value /= 10**2; result += 2; } if (value >= 10**1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import { IFundingPoolV1_1, IFundingPoolV1 } from "./IFundingPoolV1_1.sol"; import { FundingMath } from "./FundingMath.sol"; import { ArrayMath, ClampedMath } from "../Math.sol"; /// @dev A contract with the necessary storage to keep track of funding. Should /// not be used as a standalone contract, but like a mixin abstract contract FundingPool is IFundingPoolV1_1, ERC20Upgradeable { using Math for uint256; using ArrayMath for uint256[]; using SafeERC20 for IERC20Metadata; IERC20Metadata public collateralToken; /// @inheritdoc IFundingPoolV1 uint256 public collectedFees; /// @dev Keeps track of total collateral used to enter the current liquidity /// position of the funder. It is increased by the collateral amount every /// time the funder funds, and then reduced proportionally to how many LP /// shares are withdrawn during defunding. This can be considered the "cost /// basis" of the lp shares of each funder mapping(address => uint256) private funderCostBasis; /// @dev Total collateral put into funding the current LP shares uint256 private totalFunderCostBasis; /// @dev By default fees are no longer withdrawable - it's up to /// implementation to decide what to do with the fees and how to distribute /// them function withdrawFees(address /* funder */ ) public pure returns (uint256) { return 0; } /// @dev By default fees are no longer withdrawable - it's up to /// implementation to decide what to do with the fees and how to distribute /// them function feesWithdrawableBy(address /* account */ ) public pure returns (uint256) { return 0; } /// @inheritdoc IFundingPoolV1 function reserves() public view returns (uint256 collateral) { uint256 totalCollateral = collateralToken.balanceOf(address(this)); uint256 fees = collectedFees; assert(totalCollateral >= fees); return totalCollateral - fees; } // solhint-disable-next-line func-name-mixedcase function __FundingPool_init(IERC20Metadata _collateralToken) internal onlyInitializing { __ERC20_init("", ""); __FundingPool_init_unchained(_collateralToken); } // solhint-disable-next-line func-name-mixedcase function __FundingPool_init_unchained(IERC20Metadata _collateralToken) internal onlyInitializing { if (_collateralToken.decimals() > 18) revert ExcessiveCollateralDecimals(); collateralToken = _collateralToken; } /// @dev Burns the LP shares corresponding to a particular owner account /// Also note that _beforeTokenTransfer will be invoked to make sure the fee /// bookkeeping is updated for the owner. /// @param owner Account to whom the LP shares belongs to. /// @param sharesToBurn Portion of LP pool to burn. function _burnSharesOf(address owner, uint256 sharesToBurn) internal { // slither-disable-next-line dangerous-strict-equalities if (sharesToBurn == 0) revert InvalidBurnAmount(); uint256 costBasisReduction = FundingMath.calcCostBasisReduction(balanceOf(owner), sharesToBurn, funderCostBasis[owner]); funderCostBasis[owner] -= costBasisReduction; totalFunderCostBasis -= costBasisReduction; _burn(owner, sharesToBurn); } function _mintSharesFor(address receiver, uint256 collateralAdded, uint256 poolValue) internal returns (uint256 sharesMinted) { if (collateralAdded == 0) revert InvalidFundingAmount(); sharesMinted = FundingMath.calcFunding(collateralAdded, totalSupply(), poolValue); // Ensure this stays below type(uint128).max to avoid overflow in liquidity calculations uint256 costBasisAfter = funderCostBasis[receiver] + collateralAdded; if (costBasisAfter > type(uint128).max) revert ExcessiveFunding(); funderCostBasis[receiver] = costBasisAfter; totalFunderCostBasis += collateralAdded; address sender = _msgSender(); collateralToken.safeTransferFrom(sender, address(this), collateralAdded); // Ensure total shares for funding does not exceed type(uint128).max to avoid overflow uint256 sharesAfter = balanceOf(receiver) + sharesMinted; if (sharesAfter > type(uint128).max) revert ExcessiveFunding(); _mint(receiver, sharesMinted); emit FundingAdded(sender, receiver, collateralAdded, sharesMinted); } /// @dev adjust cost basis for a funder function _adjustCostBasis(address funder, uint256 adjustment) internal { funderCostBasis[funder] = funderCostBasis[funder] + adjustment; totalFunderCostBasis = totalFunderCostBasis + adjustment; } /// @dev Sets aside some collateral as fees function _retainFees(uint256 collateralFees) internal { if (collateralFees > reserves()) revert FeesExceedReserves(); if (collateralFees == 0) return; collectedFees += collateralFees; emit FeesRetained(collateralFees); } /// @dev put fees back into reserves function _unlockFees(uint256 collateralFees) internal { if (collateralFees > collectedFees) revert FeesExceedCollected(); collectedFees -= collateralFees; } /// @dev How much collateral was spent by all funders to obtain their current shares function getTotalFunderCostBasis() public view returns (uint256) { return totalFunderCostBasis; } function getFunderCostBasis(address funder) public view returns (uint256) { return funderCostBasis[funder]; } // solhint-disable-next-line ordering uint256[50] private __gap; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IChildFundingPoolV1 } from "./IChildFundingPoolV1.sol"; import { IParentFundingPoolV1 } from "./IParentFundingPoolV1.sol"; import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /// @dev A Mixin contract that provides a basic implementation of the IChildFundingPoolV1 interface abstract contract ChildFundingPool is Initializable, IChildFundingPoolV1 { using ERC165Checker for address; address private _parent; bytes4 internal constant PARENT_FUNDING_POOL_INTERFACE_ID = 0xd0632e9a; function getParentPool() public view returns (address) { return _parent; } // solhint-disable-next-line func-name-mixedcase function __ChildFundingPool_init(address parentPool) internal onlyInitializing { __ChildFundingPool_init_unchained(parentPool); } // solhint-disable-next-line func-name-mixedcase function __ChildFundingPool_init_unchained(address parentPool) internal onlyInitializing { assert(address(_parent) == address(0x0)); if (parentPool != address(0x0) && !parentPool.supportsInterface(PARENT_FUNDING_POOL_INTERFACE_ID)) { revert NotAParentPool(parentPool); } _parent = parentPool; emit ParentPoolAdded(parentPool); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import { AdminExecutorAccessUpgradeable } from "../AdminExecutorAccess.sol"; type FeeProfileID is uint256; interface FeeDistributorErrors { error FeeProfileNotFound(FeeProfileID); error InvalidFeeProfile(); /// @dev Error when a beneficiary gets nothing because the recursive /// portions have left too little to distribute. Typically should wait /// longer before distributing to increase the fund size. error UnfairDistribution(); error InvalidAmountArray(); } interface IFeeDistributorEvents { struct FeeProfile { /// @dev portion of funds out of 256 that should be sent to the child. /// The rest gets directed to the beneficiary uint8 childPortion; address beneficiary; FeeProfileID childProfile; } event FeeProfileCreated(FeeProfileID indexed profileId, FeeProfile profile); } /// @dev A pool of collateral that can be distributed to beneficiaries according /// to some fee profile - what percentage of the amount goes to whom. This is /// achieved by chaining profiles together, where a portion of the collateral /// for a profile gets sent to a beneficiary and the rest go to another profile, /// and so on until all collateral is distributed. /// /// Creating new profiles is permissionless. contract FeeDistributor is IFeeDistributorEvents, FeeDistributorErrors, AdminExecutorAccessUpgradeable { using SafeERC20 for IERC20; using Math for uint256; using EnumerableSet for EnumerableSet.UintSet; struct Transfer { FeeProfileID profileId; uint256 amount; } FeeProfileID public constant NULL_PROFILE_ID = FeeProfileID.wrap(uint256(0x0)); uint256 private constant PORTION_DIVISOR = 256; mapping(FeeProfileID => FeeProfile) public profiles; mapping(IERC20 => mapping(FeeProfileID => uint256)) public balances; EnumerableSet.UintSet private approvedProfileIds; /// @custom:oz-upgrades-unsafe-allow constructor constructor(address admin) { // The contract is not meant to be upgradeable or run behind a proxy, // but uses upgradeable base contracts because it shares some base // classes with other contracts that need to be behind a proxy initialize(admin, address(0x0)); _disableInitializers(); } /// @dev Create a new fee profile /// @return profileId the unique ID that identifies the profile function addProfile(FeeProfile calldata profile) external returns (FeeProfileID profileId) { // Do not allow the last profile in a chain not to have everything allocated to the beneficiary if (FeeProfileID.unwrap(profile.childProfile) == 0x0 && profile.childPortion > 0) { revert InvalidFeeProfile(); } profileId = FeeProfileID.wrap(uint256(keccak256(abi.encode(profile)))); profiles[profileId] = profile; emit FeeProfileCreated(profileId, profile); } function _transferToProfile(IERC20 collateralToken, FeeProfileID profileId, uint256 amount) internal { if (profiles[profileId].beneficiary == address(0x0)) revert FeeProfileNotFound(profileId); balances[collateralToken][profileId] += amount; } function transferToProfile(IERC20 collateralToken, FeeProfileID profileId, uint256 amount) external { _transferToProfile(collateralToken, profileId, amount); collateralToken.safeTransferFrom(msg.sender, address(this), amount); } function transferToProfiles(IERC20 collateralToken, FeeProfileID[] calldata profileIds, uint256[] calldata amounts) external { if (profileIds.length != amounts.length) revert InvalidAmountArray(); uint256 total = 0; for (uint256 i = 0; i < amounts.length; i++) { uint256 amount = amounts[i]; _transferToProfile(collateralToken, profileIds[i], amount); total += amount; } collateralToken.safeTransferFrom(msg.sender, address(this), total); } function distributeFees(IERC20 collateralToken, FeeProfileID profileID) external returns (uint256 totalTransferred) { mapping(FeeProfileID => uint256) storage tokenBalances = balances[collateralToken]; // Go down the entire chain of profiles and distribute the fees to all beneficiaries uint256 childAmount = 0; while (FeeProfileID.unwrap(profileID) != 0x0) { // Read these together to save on gas cost (should be in same slot) uint256 childPortion = profiles[profileID].childPortion; address beneficiary = profiles[profileID].beneficiary; uint256 balance = tokenBalances[profileID] + childAmount; if (balance == 0) break; // Using ceilDiv here, so that beneficiaries earlier in the // chain don't have an incentive to do this too early, to starve // beneficiaries further down the line childAmount = (balance * childPortion).ceilDiv(PORTION_DIVISOR); uint256 transferAmount = balance - childAmount; if (transferAmount == 0) revert UnfairDistribution(); totalTransferred += transferAmount; // All balances are distributed, either to beneficiary or child profile tokenBalances[profileID] = 0; // Re-entrancy here is ok, because the state of the contract at that // moment is "finalized" relative to the current `profileID`. Any // subsequent state variables that are modified, are for other // profileIDs which haven't been touched yet. The loop is just an // optimization to save us from manually calling this function for // all profiles down the chain one after another. // slither-disable-next-line reentrancy-no-eth collateralToken.safeTransfer(beneficiary, transferAmount); profileID = profiles[profileID].childProfile; } // Fee profile that leaves something unallocated should not be allowed assert(childAmount == 0); } function approveProfile(FeeProfileID profileId) external onlyAdmin { if (profiles[profileId].beneficiary == address(0x0)) revert FeeProfileNotFound(profileId); approvedProfileIds.add(FeeProfileID.unwrap(profileId)); } function unapproveProfile(FeeProfileID profileId) external onlyAdmin { if (profiles[profileId].beneficiary == address(0x0)) revert FeeProfileNotFound(profileId); approvedProfileIds.remove(FeeProfileID.unwrap(profileId)); } function approvedProfiles() external view returns (FeeProfileID[] memory profileIds) { uint256[] memory ids = approvedProfileIds.values(); assembly ("memory-safe") { profileIds := ids } } function initialize(address admin, address executor) private initializer { __AdminExecutor_init(admin, executor); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import { ArrayMath, ClampedMath } from "../Math.sol"; import { AmmErrors } from "./AmmErrors.sol"; import { UD60x18, UNIT, ZERO, exp, convert, unwrap, wrap } from "@prb/math/UD60x18.sol"; library UD60x18Extensions { function addScalar(UD60x18 x, uint256 y) internal pure returns (UD60x18 result) { result = wrap(unwrap(x) + y); } function subScalar(UD60x18 x, uint256 y) internal pure returns (UD60x18 result) { result = wrap(unwrap(x) - y); } function mulScalar(UD60x18 x, uint256 y) internal pure returns (UD60x18 result) { result = wrap(unwrap(x) * y); } function divScalar(UD60x18 x, uint256 y) internal pure returns (UD60x18 result) { result = wrap(unwrap(x) / y); } function ceilDivScalar(UD60x18 x, uint256 y) internal pure returns (UD60x18 result) { result = wrap(Math.ceilDiv(unwrap(x), y)); } function ceilDiv(UD60x18 x, UD60x18 y) internal pure returns (UD60x18 result) { // (x - 1) / (y + 1) result = unwrap(x) == 0 ? ZERO : addScalar(subScalar(x, 1).div(y), 1); } } library AmmMath { using Math for uint256; using ClampedMath for uint256; using ArrayMath for uint256[]; using UD60x18Extensions for UD60x18; uint256 internal constant PRECISION_DECIMALS = 18; uint256 internal constant ONE_DECIMAL = 10 ** PRECISION_DECIMALS; // The smallest exponent in the slippage formula for e ^ ((a d) / t) // Determined empirically UD60x18 internal constant MIN_EXPONENT = UD60x18.wrap(10 ** 6); // Max exponent possible that would not overflow slippage calculations UD60x18 internal constant MAX_EXPONENT = UD60x18.wrap(132e18); /// @dev Calculate the pool value given token balances and a set of fair prices /// @param balances The current balances of each outcome token in a pool /// @param fairPriceDecimals normalized prices for each outcome token /// provided externally. Any missing trailing prices are assumed to be 0. /// @return poolValue total sum of value of all tokens function calcPoolValue(uint256[] memory balances, uint256[] memory fairPriceDecimals) internal pure returns (uint256 poolValue) { // Assume any missing trailing prices are all 0 if (fairPriceDecimals.length > balances.length) revert AmmErrors.BalancePriceLengthMismatch(); uint256 totalValue = 0; uint256 normalization = 0; for (uint256 i = 0; i < fairPriceDecimals.length; ++i) { totalValue += fairPriceDecimals[i] * balances[i]; normalization += fairPriceDecimals[i]; } poolValue = totalValue.ceilDiv(normalization); } /// @dev Calculate the pool value given token balances and a set of fair prices, as well as extra collateral /// @param balances The current balances of each outcome token in a pool /// @param fairPriceDecimals normalized prices for each outcome token /// provided externally. Any missing trailing prices are assumed to be 0. /// @param collateralBalance extra collateral balance /// @return poolValue total sum of value of all tokens function calcPoolValue(uint256[] memory balances, uint256[] memory fairPriceDecimals, uint256 collateralBalance) internal pure returns (uint256 poolValue) { return calcPoolValue(balances, fairPriceDecimals) + collateralBalance; } /// @dev Calculate how many tokens result from exchanging at a flat rate. A /// minimum price is used to value output tokens, but not input tokens. /// Minimum price for output tokens avoids giving out too many if the price /// is very small. The minimum price is not symmetric, because we don't /// want to overvalue tokens that are coming in, and end up giving out more /// output tokens as a result /// @param tokensMintedDecimal quantity of input tokens to be exchanged /// @param fairPriceInDecimal price of input tokens /// @param fairPriceOutDecimal price of output tokens /// @return tokensOutDecimal quantity of tokens resulting from the exchange function calcElementwiseFairAmount( uint256 tokensMintedDecimal, uint256 fairPriceInDecimal, uint256 fairPriceOutDecimal ) internal pure returns (uint256 tokensOutDecimal) { assert(fairPriceOutDecimal > 0); tokensOutDecimal = (tokensMintedDecimal * fairPriceInDecimal) / fairPriceOutDecimal; } uint256 internal constant MIN_FLATNESS = 0.1e18; // flatness parameter cannot be lower than 0.01 uint256 internal constant MAX_FLATNESS = 2.0e18; // flatness parameter cannot exceed 2 // The lower the price, the higher the flatness of the curve (to decrease slippage) // The two are inversly related. uint256 internal constant PRICE_WITH_MAX_FLATNESS = 0.05e18; uint256 internal constant PRICE_WITH_MIN_FLATNESS = 0.5e18; uint256 internal constant PRICE_FLATNESS_LUT_INCREMENT = 0.05e18; /// @dev The new algorithm has a flatness parameter, that reduces slippage /// when balance is close to target. At flatness == 1.0 the curve is /// equivalent to e^x, and flatness == 2.0, the curve is equivalent to /// tanh(x), and as flatness approaches 0, the curve approximates the /// constant product curve. /// The flatness is adjusted based on token price - when a token is cheap, a /// larger amount of the token is taken from the balance. When a cheap token /// is bought, more tokens are removed from balance and more slippage /// occurs. In order to encourage equal bets on both sides, the slippage /// should be close for "typical" size bets. The values are derived for bets /// that are 1% of liquidity for a market. function calculateFlatness(uint256 fairPriceDecimal) internal pure returns (uint256 flatnessDecimal) { // Lookup table from price to the flatness parameter. The flatness is // derived such that the initial slippage for a low-price p token is // equivalent to slippage that you would get from a higher-price (1 - p) // token. uint256[10] memory lut = [ uint256(2.0e18), // {0.05, 2.0302}, uint256(1.83963e18), // {0.1, 1.83963}, uint256(1.69173e18), // {0.15, 1.69173}, uint256(1.54082e18), // {0.2, 1.54082}, uint256(1.37613e18), // {0.25, 1.37613}, uint256(1.19123e18), // {0.3, 1.19123}, uint256(0.979886e18), // {0.35, 0.979886}, uint256(0.734672e18), // {0.4, 0.734672}, uint256(0.445846e18), // {0.45, 0.445846}, uint256(0.1e18) // {0.5, 0.1} ]; // Price that is clamped to the min and max, and also offset such that // PRICE_WITH_MAX_FLATNESS gets remapped to 0 for indexing uint256 remappedPriceDecimal = fairPriceDecimal.clampBetween(PRICE_WITH_MAX_FLATNESS, PRICE_WITH_MIN_FLATNESS) - PRICE_WITH_MAX_FLATNESS; // index into lut and linearly interpolate uint256 index = remappedPriceDecimal / PRICE_FLATNESS_LUT_INCREMENT; uint256 blendAmount = remappedPriceDecimal % PRICE_FLATNESS_LUT_INCREMENT; uint256 nextIndex = Math.min(9, index + 1); flatnessDecimal = lut[index] - (blendAmount * (lut[index] - lut[nextIndex])) / PRICE_FLATNESS_LUT_INCREMENT; } /// @dev calculate the proportion of spread attributed to the output token. /// The less balance we have than the target, the more the spread since we /// are losing the token. function applyOutputSlippage(uint256 balance, uint256 tokensOut, uint256 targetBalance, uint256 flatnessDecimal) internal pure returns (uint256 adjustedTokensDecimal) { uint256 tokensBelowTarget; { // How many tokens from tokensOut that are above the target balance. Exchanged 1:1 uint256 tokensAboveTarget = Math.min(tokensOut, balance - Math.min(targetBalance, balance)); adjustedTokensDecimal = tokensAboveTarget * ONE_DECIMAL; balance -= tokensAboveTarget; tokensBelowTarget = tokensOut - tokensAboveTarget; } // Tokens that are now bringing us below target are run through amm to introduce slippage if (tokensBelowTarget > 0) { if (balance == 0) { return adjustedTokensDecimal; } assert(balance <= targetBalance); assert(flatnessDecimal >= MIN_FLATNESS); assert(flatnessDecimal <= MAX_FLATNESS); // a = flatness // b = balance // d = tokensBelowTarget (how many tokens we need to exchange through amm curve) // t = targetBalance // Need to calculate new balance: // E = e ^ ((a d) / t) // L = (b + a t - a b) // newBalance = (a b t) / (a b + E L - b) UD60x18 balanceDecimal = convert(balance); UD60x18 flatnessTimesBalanceDecimal = UD60x18.wrap(flatnessDecimal * balance); // (a b t) UD60x18 numeratorDecimal = flatnessTimesBalanceDecimal.mulScalar(targetBalance); // E = e ^ ((a d) / t) UD60x18 flatnessTimesTokensDecimal = UD60x18.wrap(flatnessDecimal * tokensBelowTarget); UD60x18 exponent = flatnessTimesTokensDecimal.divScalar(targetBalance); if (exponent.gte(MAX_EXPONENT)) { return adjustedTokensDecimal + (balance - 1) * ONE_DECIMAL; } // L = (b + a t - a b) UD60x18 largeTermDecimal = balanceDecimal.add(wrap(flatnessDecimal * targetBalance)).sub(flatnessTimesBalanceDecimal); UD60x18 newBalanceDecimal; if (exponent.lt(MIN_EXPONENT)) { // At extremely small values of the exponent, e^x, is close to 1 + x + x^2 / 2 // Rewriting: // E L // = (e ^ ((a d) / t)) L // =~ (1 + ((a d) / t) + ((a d) / t)^2 / 2 ) L // = L + L a d / t + L ((a d) / t)^2 / 2 // = L + L a d / t + L (a d)^2 / 2 t^2 UD60x18 intermediateTermDecimal = largeTermDecimal; largeTermDecimal = largeTermDecimal.mul(flatnessTimesTokensDecimal); intermediateTermDecimal = intermediateTermDecimal.add(largeTermDecimal.divScalar(targetBalance)); intermediateTermDecimal = intermediateTermDecimal.add( largeTermDecimal.mul(flatnessTimesTokensDecimal).divScalar(2 * targetBalance * targetBalance) ); // (a b + E L - b) UD60x18 denominatorDecimal = flatnessTimesBalanceDecimal.add(intermediateTermDecimal).sub(balanceDecimal); newBalanceDecimal = numeratorDecimal.ceilDiv(denominatorDecimal); } else if (exponent.lt(convert(80))) { UD60x18 exponentialTermDecimal = exp(exponent); UD60x18 intermediateTermDecimal = exponentialTermDecimal.mul(largeTermDecimal); // (a b + E L - b) UD60x18 denominatorDecimal = flatnessTimesBalanceDecimal.add(intermediateTermDecimal).sub(balanceDecimal); newBalanceDecimal = numeratorDecimal.ceilDiv(denominatorDecimal); } else { uint256 exponentialTerm = convert(exp(exponent)); // (a b + E L - b) uint256 denominator = convert(flatnessTimesBalanceDecimal) + Math.mulDiv(exponentialTerm, unwrap(largeTermDecimal), ONE_DECIMAL) - balance; newBalanceDecimal = wrap(unwrap(numeratorDecimal).ceilDiv(denominator)); } // Don't allow balance to go to 0; newBalanceDecimal = newBalanceDecimal.lt(UNIT) ? UNIT : newBalanceDecimal; assert(newBalanceDecimal.lte(balanceDecimal)); adjustedTokensDecimal += unwrap(balanceDecimal.sub(newBalanceDecimal)); } } function applyOutputSlippage(uint256 balance, uint256 tokensOut, uint256 targetBalance) internal pure returns (uint256 adjustedTokensDecimal) { return applyOutputSlippage(balance, tokensOut, targetBalance, ONE_DECIMAL); } /// @dev calculate the output spread. This is equivalent to output slippage /// assuming an infinitessimal trade size. tokensOutDecimal does not /// influence the amount of spread. function applyOutputSpread( uint256 balance, uint256 tokensOutDecimal, uint256 targetBalance, uint256 flatnessDecimal ) internal pure returns (uint256) { // Only apply slippage if balance below target if (balance < targetBalance) { // a = flatness // b = balance // d = tokensOut // t = targetBalance // b d (b + a t - a b) / t^2 uint256 largeTermDecimal = balance * ONE_DECIMAL + flatnessDecimal * targetBalance - flatnessDecimal * balance; uint256 numeratorDecimal = Math.mulDiv(balance * tokensOutDecimal, largeTermDecimal, ONE_DECIMAL); uint256 denominator = targetBalance * targetBalance; return numeratorDecimal / denominator; } else { return tokensOutDecimal; } } function applyOutputSpread(uint256 balance, uint256 tokensOutDecimal, uint256 targetBalance) internal pure returns (uint256) { return applyOutputSpread(balance, tokensOutDecimal, targetBalance, ONE_DECIMAL); } /// @dev Calculate the amount of tokensOut given the amount of tokensMinted. /// This code is generic with respect to how many outcomes have prices. /// @param tokensMinted amount of tokens minted that we are trying to exchange /// @param indexOut the index of the outcome token we are trying to buy /// @param targetBalance the target balance of each outcome token. We assume /// equal target balance is optimal, so it can be represented by a single /// value rather than an array. All token balances should ideally equal this /// value /// @param collateralBalance Extra collateral available to mint more tokens /// @param balances The current balances of each outcome token in the pool /// @param fairPriceDecimals normalized prices for each outcome token /// provided externally. Any missing trailing prices are assumed to be 0. /// @return tokensOut how many tokens are swapped for the other minted tokens /// @return newPoolValue given the fair prices, what is the overall pool value after the exchange function calcBuyAmountV3( uint256 tokensMinted, uint256 indexOut, uint256 targetBalance, uint256 collateralBalance, uint256[] memory balances, uint256[] memory fairPriceDecimals ) internal pure returns (uint256 tokensOut, uint256 newPoolValue) { // If balances is longer than fair prices, that implies some tokens are worth 0 (such as refund tokens). // They are inconsequential to the calculation here. if (fairPriceDecimals.length > balances.length) revert AmmErrors.BalancePriceLengthMismatch(); // Also implies that even if indexOut is within the length of balances, // if it is beyond the length of fairPrices, then the price of that // token is 0. Buying 0-price tokens through the AMM should not be // possible if (indexOut >= fairPriceDecimals.length) revert AmmErrors.InvalidOutcomeIndex(); if (targetBalance == 0) revert AmmErrors.NoLiquidityAvailable(); // High level overview: // 1. We exchange these tokens at a flat rate according to fairPrices. This ignores token balances. // 2. We apply an AMM curve on the output tokens, relative to a target balance uint256 tokensOutDecimal = 0; uint256 newPoolValueDecimal = 0; for (uint256 i = 0; i < fairPriceDecimals.length; i++) { if (i == indexOut) continue; // 1. flat exchange uint256 inputTokensDecimal = tokensMinted * ONE_DECIMAL; tokensOutDecimal += calcElementwiseFairAmount(inputTokensDecimal, fairPriceDecimals[i], fairPriceDecimals[indexOut]); newPoolValueDecimal += (balances[i] + collateralBalance + tokensMinted) * fairPriceDecimals[i]; } // 2. slippage for the out pool uint256 flatnessDecimal = calculateFlatness(fairPriceDecimals[indexOut]); tokensOutDecimal = applyOutputSlippage( balances[indexOut] + collateralBalance, tokensOutDecimal / ONE_DECIMAL, targetBalance, flatnessDecimal ); tokensOut = tokensOutDecimal / ONE_DECIMAL; newPoolValueDecimal += (balances[indexOut] + collateralBalance - tokensOut) * fairPriceDecimals[indexOut]; newPoolValue = newPoolValueDecimal.ceilDiv(ONE_DECIMAL); } /// @dev Calculate the current prices of all tokens, only with spread, and /// no slippage. This can be used on the frontend to compare the price /// impact of trade size. This code is generic with respect to how many /// outcomes have prices. /// @param targetBalance the target balance of each outcome token. We assume /// equal target balance is optimal, so it can be represented by a single /// value rather than an array. All token balances should ideally equal this /// value /// @param collateralBalance Extra collateral available to mint more tokens /// @param balances The current balances of each outcome token in the pool /// @param fairPriceDecimals normalized prices for each outcome token /// provided externally. Any missing trailing prices are assumed to be 0. /// @return spontaneousPriceDecimals the modified prices of each token that /// include the spread. Will not sum to ONE_DECIMAL. function calcSpontaneousPricesV3( uint256 targetBalance, uint256 collateralBalance, uint256[] memory balances, uint256[] memory fairPriceDecimals ) internal pure returns (uint256[] memory spontaneousPriceDecimals) { if (fairPriceDecimals.length > balances.length) revert AmmErrors.BalancePriceLengthMismatch(); if (targetBalance == 0) revert AmmErrors.NoLiquidityAvailable(); spontaneousPriceDecimals = new uint256[](fairPriceDecimals.length); uint256 tokensInDecimal = ONE_DECIMAL; for (uint256 indexOut = 0; indexOut < spontaneousPriceDecimals.length; indexOut++) { // Calculate the spontaneous price for each outcome // Can be calculated by exchanging ONE_DECIMAL tokens at the // spontaneous price to get number of tokens out. Then the // reciprocal is the price uint256 balanceOut = balances[indexOut] + collateralBalance; uint256 tokensOutDecimal = 0; for (uint256 indexIn = 0; indexIn < fairPriceDecimals.length; indexIn++) { if (indexOut == indexIn) continue; // 1. flat exchange tokensOutDecimal += calcElementwiseFairAmount(tokensInDecimal, fairPriceDecimals[indexIn], fairPriceDecimals[indexOut]); } // 2. spread for the out pool uint256 flatnessDecimal = calculateFlatness(fairPriceDecimals[indexOut]); tokensOutDecimal = applyOutputSpread(balanceOut, tokensOutDecimal, targetBalance, flatnessDecimal); // To get the price, need to consider total tokens acquired during a purchase. // Typically tokens are split among all outcomes, and the unwanted // ones are exchanged for tokensOut. The total at the end of output // tokens also include the tokensIn amount from the split uint256 tokensBoughtDecimal = tokensOutDecimal + tokensInDecimal; spontaneousPriceDecimals[indexOut] = (tokensInDecimal * ONE_DECIMAL) / tokensBoughtDecimal; } } /// @dev describes operations to be done with respect to parent funding in /// order to maintain the right amount of reserves locally vs in the parent struct ParentOperations { uint256 collateralToRequestFromParent; uint256 collateralToReturnToParent; uint256 sharesToBurnOfParent; } struct TargetContext { /// @dev target the target balance used by all AMM calculations uint256 target; /// @dev all collateral available to be used to mint tokens, including that from the parent uint256 globalReserves; uint256[] balances; } /// @dev Return the index into the balance array where the refund outcome is. /// Documents the assumption in one place. function getRefundIndex(uint256[] memory outcomeArray) internal pure returns (uint256 refundIndex) { refundIndex = outcomeArray.length - 1; } function getRefundIndex(TargetContext memory targetContext) internal pure returns (uint256) { return getRefundIndex(targetContext.balances); } struct BuyContext { uint256 investmentMinusFees; uint256 tokensExchanged; uint256 newPoolValue; uint256 refund; } /// @dev Calculate how the state of the Amm Pool should change as a result /// of a buy order. This algorithm assumes a few more things than others in /// this file: /// - There is a parent pool from which we can request collateral, or return /// any excess /// - Besides buying a particular priced outcome, we are also taking care of /// a mutually exclusive refund outcome /// - The refund outcome is assumed to be the last index in the balances array /// @param indexOut the index of the bought token /// @param targetContext the current state of the pool - token balances, /// reserves, and value target. This is modified in place to reflect the /// state after the fact /// @param buyContext the information from the buy order - how much was paid, and how much was received /// @param parentShares how many parent shares exist (assumed that ALL shares are parent shares) /// @return outcomeTokensBought the total amount of tokens the buyer should receive /// @return tokensToMint how many tokens should be minted across all outcomes to fulfil the order /// @return parentOps requests and returns of collateral to a parent pool function calcMarketPoolChanges( uint256 indexOut, uint256 parentShares, TargetContext memory targetContext, BuyContext memory buyContext ) internal pure returns (uint256 outcomeTokensBought, uint256 tokensToMint, ParentOperations memory parentOps) { parentOps = ParentOperations(0, 0, 0); uint256 investmentMinusFees = buyContext.investmentMinusFees; // Last index is assumed to be the refund outcome uint256 refundIndex = getRefundIndex(targetContext); { outcomeTokensBought = buyContext.tokensExchanged + investmentMinusFees; uint256 refundTokensToMint = buyContext.refund.subClamp(targetContext.balances[refundIndex]); uint256 outcomeTokensToMint = outcomeTokensBought.subClamp(targetContext.balances[indexOut]); tokensToMint = Math.max(refundTokensToMint, outcomeTokensToMint); } // check if we don't have enough tokens, or too many if (tokensToMint >= investmentMinusFees) { unchecked { parentOps.collateralToRequestFromParent = tokensToMint - investmentMinusFees; } } else { // In this case all parent funding is tied up in tokens. The // leftover collateral from the buyer's investment is distributed // back to the parent. Any shares owned by other accounts (due to // removing liquidity in the form of child chares), do not have a // claim on any collateral, only tokens. This is assymetric on // purpose. // - Less complex, less gas cost // - Parent pool is main funder of collateral. Other accounts can // remove liquidity in the form of risk (pure tokens) if they want it. // parent is eligible to get all of leftover collateral uint256 investmentLeftOver; unchecked { investmentLeftOver = investmentMinusFees - tokensToMint; } // if any individual funders removed liquidity in terms of child // shares, they should have immediately been ejected and given // tokens directly. No individual funder shares should be lingering assert(parentShares > 0); uint256 tokenAndLocalReservesValue = (buyContext.newPoolValue - targetContext.globalReserves); parentOps.collateralToReturnToParent = investmentLeftOver; // number of shares to return depends on proportion of the collateral we are returning to value in market parentOps.sharesToBurnOfParent = (investmentLeftOver * parentShares) / tokenAndLocalReservesValue; } // Update TargetContext so it reflects the new state of the market targetContext.globalReserves = targetContext.globalReserves + investmentMinusFees - tokensToMint; for (uint256 i = 0; i < targetContext.balances.length; i++) { targetContext.balances[i] += tokensToMint; } targetContext.balances[indexOut] -= outcomeTokensBought; targetContext.balances[refundIndex] -= buyContext.refund; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import { ClampedMath } from "../Math.sol"; import { FundingErrors } from "./FundingErrors.sol"; library FundingMath { using ClampedMath for uint256; using Math for uint256; uint256 internal constant SHARE_PRECISION_DECIMALS = 4; uint256 internal constant SHARE_PRECISION_OFFSET = 10 ** SHARE_PRECISION_DECIMALS; /// @dev We always try to keep the pools balanced. There are never any /// "sendBackAmounts" like in a typical constant product AMM where the /// balances need to be maintained to determine the prices. We want to /// use all the available collateral for liquidity no matter what the /// probabilities of the outcomes are. /// @param collateralAdded how much collateral the funder is adding to the pool /// @param totalShares the current number of liquidity pool shares in circulation /// @param poolValue total sum of value of all tokens /// @return sharesMinted how many liquidity pool shares should be minted function calcFunding(uint256 collateralAdded, uint256 totalShares, uint256 poolValue) internal pure returns (uint256 sharesMinted) { // To prevent inflation attack. See articles and reference implementation: // https://mixbytes.io/blog/overview-of-the-inflation-attack // https://docs.openzeppelin.com/contracts/4.x/erc4626#defending_with_a_virtual_offset // https://github.com/boringcrypto/YieldBox/blob/master/contracts/YieldBoxRebase.sol#L24-L29 poolValue++; totalShares += SHARE_PRECISION_OFFSET; assert(totalShares > 0); // mint LP tokens proportional to how much value the new investment // brings to the pool sharesMinted = (collateralAdded * totalShares).ceilDiv(poolValue); } /// @dev Calculate how much of an asset in the liquidity pool to return to a funder. /// @param sharesToBurn how many liquidity pool shares a funder wants to burn /// @param totalShares the current number of liquidity pool shares in circulation /// @param balance number of an asset in the pool /// @return sendAmount how many asset tokens to give back to funder function calcReturnAmount(uint256 sharesToBurn, uint256 totalShares, uint256 balance) internal pure returns (uint256 sendAmount) { if (sharesToBurn > totalShares) revert FundingErrors.InvalidBurnAmount(); if (sharesToBurn == 0) return sendAmount; sendAmount = (balance * sharesToBurn) / totalShares; } /// @dev Calculate how much of the assets in the liquidity pool to return to a funder. /// @param sharesToBurn how many liquidity pool shares a funder wants to burn /// @param totalShares the current number of liquidity pool shares in circulation /// @param balances number of each asset in the pool /// @return sendAmounts how many asset tokens to give back to funder function calcReturnAmounts(uint256 sharesToBurn, uint256 totalShares, uint256[] memory balances) internal pure returns (uint256[] memory sendAmounts) { if (sharesToBurn > totalShares) revert FundingErrors.InvalidBurnAmount(); sendAmounts = new uint256[](balances.length); if (sharesToBurn == 0) return sendAmounts; for (uint256 i = 0; i < balances.length; i++) { sendAmounts[i] = (balances[i] * sharesToBurn) / totalShares; } } /// @dev Calculate how much to reduce the cost basis due to shares being burnt /// @param funderShares how many liquidity pool shares a funder currently owns /// @param sharesToBurn how many liquidity pool shares a funder currently owns /// @param funderCostBasis how much collateral was spent acquiring the funder's liquidity pool shares /// @return costBasisReduction the amount by which to reduce the costbasis for the funder function calcCostBasisReduction(uint256 funderShares, uint256 sharesToBurn, uint256 funderCostBasis) internal pure returns (uint256 costBasisReduction) { if (sharesToBurn > funderShares) revert FundingErrors.InvalidBurnAmount(); costBasisReduction = funderShares == 0 ? 0 : (funderCostBasis * sharesToBurn) / funderShares; } /// @dev Calculate how many shares to burn for an asset, so that how many /// parent shares are removed are not a larger proportion of funder's /// shares, than the proportion of the asset value among other assets. /// /// i.e. /// ((funderSharesRemovedAsAsset + sharesBurnt) / funderTotalShares) /// <= /// (assetValue / totalValue) /// /// @param funderTotalShares Total parent shares owned and removed by funder /// @param sharesToBurn How many funder shares we're trying to burn /// @param funderSharesRemovedAsAsset quantity of shares already removed as the asset /// @param assetValue current value of the asset /// @param totalValue the total value to compare the asset value to. The /// ratio of asset value to this total is what sharesBurnt should not exceed /// @return sharesBurnt quantity of shares that can be burnt given the above restrictions function calcMaxParentSharesToBurnForAsset( uint256 funderTotalShares, uint256 sharesToBurn, uint256 funderSharesRemovedAsAsset, uint256 assetValue, uint256 totalValue ) internal pure returns (uint256 sharesBurnt) { uint256 maxShares = ((funderTotalShares * assetValue).ceilDiv(totalValue)).subClamp(funderSharesRemovedAsAsset); sharesBurnt = Math.min(sharesToBurn, maxShares); if (sharesBurnt > 0) { // This is a re-arrangement of the inequality given in the // description. It only applies when we are trying to give out some // shares. If sharesBurnt is 0, that means we've already exceeded // how many shares we can safely burn, so the inequality is // violated. // The -1 is due to the rounding up in ceilDiv above, used to // prevent never being able to burn the last remaining share assert(((funderSharesRemovedAsAsset + sharesBurnt - 1) * totalValue) < (assetValue * funderTotalShares)); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface AmmErrors { error InvalidOutcomeIndex(); error NoLiquidityAvailable(); error BalancePriceLengthMismatch(); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface FundingErrors { error InvalidFundingAmount(); error InvalidBurnAmount(); error InvalidReceiverAddress(); error PoolValueZero(); /// @dev Fee is is or exceeds 100% error InvalidFee(); /// @dev Trying to retain fees that exceed the current reserves error FeesExceedReserves(); /// @dev Trying to unlock more fees than currently collected error FeesExceedCollected(); /// @dev Funding is so large, that it may lead to overflow errors in future /// actions error ExcessiveFunding(); /// @dev Collateral ERC20 decimals exceed 18, leading to potential overflows error ExcessiveCollateralDecimals(); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; /// @dev Functions to deal with 16bit prices packed into `bytes`. /// In prediction markets, prices are within the range [0-1]. As such, arbitrary /// magnitude and precision are not necessary. By restricting prices to be fixed /// point integers between 0 and 1e4, we get: /// - Prices fit in 16 bits /// - Can be easily renormalized to 1e18 via a multiplier /// /// The 16bit prices are packed back to back and encoded in big-endian format. /// /// Some notes: /// /// Packing/unpacking is done manually and not via solidity's uint16[]. /// uint16[] arrays are still encoded with all the padding. Additionally, /// working directly with uint16 data types is less efficient than uint256, due /// to bit shifting and masking that is implicitly done library PackedPrices { using Math for uint256; /// @dev a divisor that fits in 16 bits, and easily divides into 1e18 uint256 internal constant DIVISOR = 1e4; /// @dev divisor for majority of decimal calculations uint256 internal constant ONE_DECIMAL = 1e18; /// @dev We store packed prices in 16 bits with a divisor of 1e4. AMM math /// relies on prices having divisor of 1e18. We can go directly from one to /// the other by multiplying by 1e14. uint256 internal constant DECIMAL_CONVERSION_FACTOR = 1e14; /// @dev How many bits to shift to convert between big-endian uint16 and uint256 uint256 internal constant SHIFT_BITS = 30 * 8; /// @dev Given a packed price byte array, unpack into a decimal price array with 1e18 divisor /// @param packedPrices packed byte array /// @return priceDecimals unpacked price array of prices normalized to 1e18 function toPriceDecimals(bytes memory packedPrices) internal pure returns (uint256[] memory priceDecimals) { unchecked { uint256 length = packedPrices.length / 2; priceDecimals = new uint256[](length); for (uint256 i; i < length; i++) { uint256 chunk; uint256 offset = 32 + i * 2; assembly ("memory-safe") { chunk := mload(add(packedPrices, offset)) } priceDecimals[i] = (chunk >> SHIFT_BITS) * DECIMAL_CONVERSION_FACTOR; } } } /// @dev Given a packed price byte array in storage, unpack into a decimal price array with 1e18 divisor /// @param packedPrices packed byte array storage pointer /// @return priceDecimals unpacked price array of prices normalized to 1e18 function toPriceDecimalsFromStorage(bytes storage packedPrices) internal pure returns (uint256[] memory) { // Much easier to copy the byte array into memory first, and then // perform the conversion from memory array, than doing it directly from // storage. // This is because the storage load instruction `SLOAD` costs 200 gas, // while the memory load instruction `MLOAD` costs only 3. The // drastically simpler code that loads each integer one at a time would // be extremely costly with SLOAD, and would require a different // algorithm that amounts to copying into memory first to minimize SLOAD // instructions. return toPriceDecimals(packedPrices); } /// @dev Given an array of integers, packs them into a byte array of 16bit values. /// Integers are taken as-is, with no re-normalization. /// @param prices array of integers less than or equal to type(uint16).max . Otherwise truncation will occur /// @param divisor what to divide prices by before packing /// @return packedPrices packed byte array function toPackedPrices(uint256[] memory prices, uint256 divisor) internal pure returns (bytes memory packedPrices) { unchecked { uint256 length = prices.length; // set the size of bytes array packedPrices = new bytes(length * 2); for (uint256 i; i < length; i++) { uint256 adjustedPrice = prices[i] / divisor; assert(adjustedPrice <= type(uint16).max); uint256 chunk = adjustedPrice << SHIFT_BITS; uint256 offset = 32 + i * 2; assembly { mstore(add(packedPrices, offset), chunk) } } } } /// @dev Sums the values in the packed price byte array /// @param packedPrices the byte array that encodes the packed prices /// @return result the sum of the decoded prices function sum(bytes memory packedPrices) internal pure returns (uint256 result) { unchecked { uint256 length = packedPrices.length / 2; for (uint256 i; i < length; i++) { uint256 chunk; uint256 offset = 32 + i * 2; assembly ("memory-safe") { chunk := mload(add(packedPrices, offset)) } result += chunk >> SHIFT_BITS; } } } function arrayLength(bytes memory packedPrices) internal pure returns (uint256) { return packedPrices.length / 2; } function valueAtIndex(bytes memory packedPrices, uint256 index) internal pure returns (uint256) { uint256 chunk; uint256 offset = 32 + index * 2; assembly ("memory-safe") { chunk := mload(add(packedPrices, offset)) } return (chunk >> SHIFT_BITS); } // TODO: potentially optimize reading directly from storage }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; type QuestionID is bytes32; type ConditionID is bytes32; type CollectionID is bytes32; library CTHelpers { /// @dev Constructs a condition ID from an oracle, a question ID, and the /// outcome slot count for the question. /// @param oracle The account assigned to report the result for the prepared condition. /// @param questionId An identifier for the question to be answered by the oracle. /// @param outcomeSlotCount The number of outcome slots which should be used /// for this condition. Must not exceed 256. function getConditionId(address oracle, QuestionID questionId, uint256 outcomeSlotCount) internal pure returns (ConditionID) { assert(outcomeSlotCount < 257); // `<` uses less gas than `<=` return ConditionID.wrap(keccak256(abi.encodePacked(oracle, questionId, outcomeSlotCount))); } /// @dev Constructs an outcome collection ID /// @param conditionId Condition ID of the outcome collection /// @param index outcome index function getCollectionId(ConditionID conditionId, uint256 index) internal pure returns (CollectionID) { return CollectionID.wrap(keccak256(abi.encodePacked(conditionId, index))); } /// @dev Constructs a position ID from a collateral token and an outcome /// collection. These IDs are used as the ERC-1155 ID for this contract. /// @param collateralToken Collateral token which backs the position. /// @param collectionId ID of the outcome collection associated with this position. function getPositionId(IERC20 collateralToken, CollectionID collectionId) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(collateralToken, collectionId))); } /// @dev Constructs all position ID in a condition, for a collateral token. /// These IDs are used as the ERC-1155 ID for the ConditionalTokens contract. /// @param collateralToken Collateral token which backs the position. /// @param conditionId ID of the condition associated with all positions /// @param outcomeSlotCount number of outcomes in the condition function getPositionIds(IERC20 collateralToken, ConditionID conditionId, uint256 outcomeSlotCount) internal pure returns (uint256[] memory positionIds) { positionIds = new uint256[](outcomeSlotCount); for (uint256 i = 0; i < outcomeSlotCount; i++) { positionIds[i] = getPositionId(collateralToken, getCollectionId(conditionId, i)); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { require(!paused(), "Pausable: paused"); } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { require(paused(), "Pausable: not paused"); } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^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 { 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) { return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^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; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv( uint256 x, uint256 y, uint256 denominator, Rounding rounding ) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // 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 + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10**64) { value /= 10**64; result += 64; } if (value >= 10**32) { value /= 10**32; result += 32; } if (value >= 10**16) { value /= 10**16; result += 16; } if (value >= 10**8) { value /= 10**8; result += 8; } if (value >= 10**4) { value /= 10**4; result += 4; } if (value >= 10**2) { value /= 10**2; result += 2; } if (value >= 10**1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import { FundingErrors } from "./FundingErrors.sol"; interface FundingPoolEvents { /// @notice Collateral is added to the liquidity pool /// @param sender the account that initiated and supplied the collateral for the funding /// @param funder the account that receives the liquidity pool shares /// @param collateralAdded the quantity of collateral supplied to the pool /// @param sharesMinted the quantity of liquidity pool shares created as sa result of the funding event FundingAdded(address indexed sender, address indexed funder, uint256 collateralAdded, uint256 sharesMinted); /// @notice Funding is removed as a mix of tokens and collateral /// @param funder the owner of liquidity pool shares /// @param collateralRemoved the quantity of collateral removed from the pool proportional to funder's shares /// @param tokensRemoved the quantity of tokens removed from the pool proportional to funder's shares. Can be empty /// @param sharesBurnt the quantity of liquidity pool shares burnt event FundingRemoved( address indexed funder, uint256 collateralRemoved, uint256[] tokensRemoved, uint256 sharesBurnt ); /// @notice Funding is removed as a specific token, referred to by an id /// @param funder the owner of liquidity pool shares /// @param tokenId an id that identifies a single asset token in the pool. Up to the pool to decide the meaning of the id /// @param tokensRemoved the quantity of a token removed from the pool /// @param sharesBurnt the quantity of liquidity pool shares burnt event FundingRemovedAsToken( address indexed funder, uint256 indexed tokenId, uint256 tokensRemoved, uint256 sharesBurnt ); /// @notice Some portion of collateral was withdrawn for fee purposes event FeesWithdrawn(address indexed funder, uint256 collateralRemovedFromFees); /// @notice Some portion of collateral was retained for fee purposes event FeesRetained(uint256 collateralAddedToFees); } /// @dev A funding pool deals with 3 different assets: /// - collateral with which to make investments (ERC20 tokens of general usage, e.g. USDT, USDC, DAI, etc.) /// - shares which represent the stake in the fund (ERC20 tokens minted and burned by the funding pool) /// - tokens that are the actual investments (e.g. ERC1155 conditional tokens) interface IFundingPoolV1 is IERC20Upgradeable, FundingErrors, FundingPoolEvents { /// @notice Funds the market with collateral from the sender /// @param collateralAdded Amount of funds from the sender to transfer to the market function addFunding(uint256 collateralAdded) external returns (uint256 sharesMinted); /// @notice Funds the market on behalf of receiver. /// @param receiver Account that receives LP tokens. /// @param collateralAdded Amount of funds from the sender to transfer to the market function addFundingFor(address receiver, uint256 collateralAdded) external returns (uint256 sharesMinted); /// @notice Withdraws the fees from a particular liquidity provider. /// @param funder Account address to withdraw its available fees. function withdrawFees(address funder) external returns (uint256 collateralRemovedFromFees); /// @notice Returns the amount of fee in collateral to be withdrawn by the liquidity providers. /// @param account Account address to check for fees available. function feesWithdrawableBy(address account) external view returns (uint256 collateralFees); /// @notice How much collateral is available that is not set aside for fees function reserves() external view returns (uint256 collateral); /// @notice Returns the current collected fees on this market. function collectedFees() external view returns (uint256 collateralFees); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface UpdateFairPricesEvents { event MarketPricesUpdated(uint256[] fairPriceDecimals); event MarketMinPriceUpdated(uint128 minPriceDecimal); } interface IUpdateFairPrices is UpdateFairPricesEvents { function updateFairPrices(uint256[] calldata fairPriceDecimals) external; function updateMinPrice(uint128 minPriceDecimal) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface ConditionalTokensErrors { error ConditionAlreadyPrepared(); error PayoutAlreadyReported(); error PayoutsAreAllZero(); error InvalidOutcomeSlotCountsArray(); error InvalidPayoutArray(); error ResultNotReceivedYet(); error InvalidIndex(); error NoPositionsToRedeem(); error ConditionNotFound(); error InvalidAmount(); error InvalidOutcomeSlotsAmount(); error InvalidQuantities(); error InvalidPrices(); error InvalidConditionOracle(address conditionOracle); error MustBeCalledByOracle(); error InvalidHaltTime(); /// @dev using unapproved ERC20 token with protocol error InvalidERC20(); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by // decrementing then incrementing. _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; // Overflow not possible: amount <= accountBalance <= totalSupply. _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IFundingPoolV1 } from "./IFundingPoolV1.sol"; /// @dev An extension to IFundingPoolV1 that adds more methods to inspect cost basis, interface IFundingPoolV1_1 is IFundingPoolV1 { /// @dev How much collateral was spent by a funder to obtain their current shares function getFunderCostBasis(address funder) external returns (uint256); /// @dev How much collateral was spent by all funders to obtain their current shares function getTotalFunderCostBasis() external returns (uint256); /// @dev Current estimated value in collateral of the entire pool function getPoolValue() external returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IERC165Upgradeable } from "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; interface ChildFundingPoolErrors { error NotAParentPool(address parentPool); } interface ChildFundingPoolEvents { event ParentPoolAdded(address indexed parentPool); } /// @dev Interface for a funding pool that can be added as a child to a Parent Funding pool interface IChildFundingPoolV1 is IERC165Upgradeable, ChildFundingPoolEvents, ChildFundingPoolErrors { function getParentPool() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import { IERC165Upgradeable } from "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import { ContextUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; interface ParentFundingPoolErrors { /// @dev Occurs when a child pool does not support the necessary interfaces error NotAChildPool(address childPool); /// @dev Occurs when a child pool is not approved to perform the operation error ChildPoolNotApproved(address childPool); /// @dev Occurs when batch operations have mismatching array lengths error InvalidBatchLength(); } interface ParentFundingPoolEvents { /// @dev A child pool approval was added or removed event ChildPoolApproval(address indexed childPool, uint256 approved); /// @dev Limit of how much can be requested has changed event RequestLimitChanged(uint256 limit); /// @dev A child pool has requested some funds, and the parent gives it. The /// value locked into the child is exactly equal to the collateralGiven event FundingGiven(address indexed childPool, uint256 collateralGiven); /// @dev A child pool has returned some funding, unlocking some value /// @param childPool the child pool that borrowed the funds /// @param collateralReturned quantity of collateral given back to the pool /// @param valueUnlocked due to profit/loss, collateral returned may not /// equal in value to what was originally given. valueUnlocked corresponds /// to the portion of original collateral that is returned event FundingReturned(address indexed childPool, uint256 collateralReturned, uint256 valueUnlocked); } /// @dev Interface for a FundingPool that allows child FundingPools to request/return funds interface IParentFundingPoolV1 is IERC165Upgradeable, ParentFundingPoolEvents, ParentFundingPoolErrors { /// @dev childPool should support IFundingPoolV1 interface function setApprovalForChild(address childPool, uint256 approval) external; /// @dev Called by an approved child pool, to request collateral /// NOTE: assumes msg.sender supports IFundingPool that is approved /// @param collateralRequested how much collateral is requested by the childPool /// @return collateralAdded Actual amount given (which may be lower than collateralRequested) /// @return sharesMinted How many child shares were given due to the funding function requestFunding(uint256 collateralRequested) external returns (uint256 collateralAdded, uint256 sharesMinted); /// @dev Notify parent after voluntarily returning back some collateral, and burning corresponding shares /// @param collateralReturned how much collateral funding was transferred from child to parent /// @param sharesBurnt how many child shares were burnt as a result function fundingReturned(uint256 collateralReturned, uint256 sharesBurnt) external; /// @dev Notify parent after voluntarily returning back some fees /// @param fees how much fees (in collateral) was transferred from child to parent function feesReturned(uint256 fees) external; /// @dev What is the maximum amount of collateral a child can request from the parent function getApprovalForChild(address childPool) external view returns (uint256 approval); /// @dev See how much funding is available for a particular child pool. /// Takes into account how much has already been consumed from the approval, /// and how much collateral is available in the pool. /// @param childPool address of the childPool /// @return availableFunding how much collateral can be requested, that takes into account any gains or losses /// @return targetFunding The target funding amount that can be requested, without gains or losses function getAvailableFunding(address childPool) external view returns (uint256 availableFunding, uint256 targetFunding); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol) // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js. pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. * * [WARNING] * ==== * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure * unusable. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. * * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an * array of EnumerableSet. * ==== */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { bytes32[] memory store = _values(set._inner); bytes32[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values in the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } }
// SPDX-License-Identifier: 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 // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT 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_SD59x18 } from "../sd59x18/Constants.sol"; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { uMAX_UD2x18 } from "../ud2x18/Constants.sol"; import { UD2x18 } from "../ud2x18/ValueType.sol"; import { UD60x18 } from "./ValueType.sol"; /// @notice Casts a UD60x18 number into SD1x18. /// @dev Requirements: /// - x must be less than or equal to `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 UD2x18. /// @dev Requirements: /// - x must be less than or equal to `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 SD59x18. /// @dev Requirements: /// - x must be less than or equal to `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 must be less than or equal to `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 must be less than or equal to `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 must be less than or equal to `MAX_UD60x18 / UNIT`. /// /// @param x The basic integer to convert. /// @param 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 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 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 1. 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 must be less than or equal to `MAX_WHOLE_UD60x18`. /// /// @param x The UD60x18 number to ceil. /// @param 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. /// @param 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 must be less than 133_084258667509499441. /// /// @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 must be less than 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. /// @param 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. /// @param 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 must be greater than zero. /// /// @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 greater than `UNIT`, use the standard formula. if (xUint > uUNIT) { result = exp2(mul(log2(x), y)); } // Conversely, if x is less than `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 must be less than `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.intoUD2x18, Casting.intoSD59x18, 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.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 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 { 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 maximum 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); int256 constant uUNIT = 1e18;
// 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.intoUD2x18, Casting.intoUD60x18, Casting.intoUint256, Casting.intoUint128, Casting.intoUint40, Casting.unwrap } for SD1x18 global;
// 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 The maximum input permitted in {exp2}. int256 constant uEXP2_MAX_INPUT = 192e18 - 1; SD59x18 constant EXP2_MAX_INPUT = SD59x18.wrap(uEXP2_MAX_INPUT); /// @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 "./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.intoUD2x18, 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 { 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. uint256 constant uUNIT = 1e18; UD2x18 constant UNIT = UD2x18.wrap(1e18);
// 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.intoSD1x18, Casting.intoSD59x18, Casting.intoUD60x18, Casting.intoUint256, Casting.intoUint128, Casting.intoUint40, Casting.unwrap } for UD2x18 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 { UD2x18 } from "../ud2x18/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 the domain of SD1x18 is a subset of SD59x18. function intoSD59x18(SD1x18 x) pure returns (SD59x18 result) { result = SD59x18.wrap(int256(SD1x18.unwrap(x))); } /// @notice Casts an SD1x18 number into UD2x18. /// - x must be positive. function intoUD2x18(SD1x18 x) pure returns (UD2x18 result) { int64 xInt = SD1x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD1x18_ToUD2x18_Underflow(x); } result = UD2x18.wrap(uint64(xInt)); } /// @notice Casts an SD1x18 number into UD60x18. /// @dev Requirements: /// - x must be positive. 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 uint256. /// @dev Requirements: /// - x must be positive. 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 uint128. /// @dev Requirements: /// - x must be positive. 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 uint40. /// @dev Requirements: /// - x must be positive. /// - x must be less than or equal to `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 "./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_UD2x18 } from "../ud2x18/Constants.sol"; import { UD2x18 } from "../ud2x18/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 must be greater than or equal to `uMIN_SD1x18`. /// - x must be less than or equal to `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 UD2x18. /// @dev Requirements: /// - x must be positive. /// - x must be less than or equal to `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 UD60x18. /// @dev Requirements: /// - x must be positive. 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 must be positive. 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 must be positive. /// - x must be less than or equal to `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 must be positive. /// - x must be less than or equal to `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 { 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, 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 must be greater than `MIN_SD59x18`. /// /// @param x The SD59x18 number for which to calculate the absolute value. /// @param 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 must be less than or equal to `MAX_WHOLE_SD59x18`. /// /// @param x The SD59x18 number to ceil. /// @param 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. /// @param 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 must be less than 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(); // 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 is less than -59_794705707972522261, the result is zero. /// /// Requirements: /// - x must be less than 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 this is truncated to zero. if (xInt < -59_794705707972522261) { 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 must be greater than or equal to `MIN_WHOLE_SD59x18`. /// /// @param x The SD59x18 number to floor. /// @param 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. /// @param 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 must be greater than zero. /// /// @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 cannot be negative, since complex numbers are not supported. /// - x must be less than `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 "../Common.sol" as Common; import "./Errors.sol" as Errors; import { uMAX_SD1x18 } from "../sd1x18/Constants.sol"; import { SD1x18 } from "../sd1x18/ValueType.sol"; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { UD60x18 } from "../ud60x18/ValueType.sol"; import { UD2x18 } from "./ValueType.sol"; /// @notice Casts a UD2x18 number into SD1x18. /// - x must be less than or equal to `uMAX_SD1x18`. function intoSD1x18(UD2x18 x) pure returns (SD1x18 result) { uint64 xUint = UD2x18.unwrap(x); if (xUint > uint64(uMAX_SD1x18)) { revert Errors.PRBMath_UD2x18_IntoSD1x18_Overflow(x); } result = SD1x18.wrap(int64(xUint)); } /// @notice Casts a UD2x18 number into SD59x18. /// @dev There is no overflow check because the domain of UD2x18 is a subset of 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 the domain of UD2x18 is a subset of 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 the domain of UD2x18 is a subset of 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 the domain of UD2x18 is a subset of uint256. function intoUint256(UD2x18 x) pure returns (uint256 result) { result = uint256(UD2x18.unwrap(x)); } /// @notice Casts a UD2x18 number into uint40. /// @dev Requirements: /// - x must be less than or equal to `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 { SD1x18 } from "./ValueType.sol"; /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in UD2x18. error PRBMath_SD1x18_ToUD2x18_Underflow(SD1x18 x); /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in UD60x18. error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x); /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint128. error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x); /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint256. error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x); /// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint40. error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x); /// @notice Thrown when trying to cast a 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 { 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 a UD60x18 number that doesn't fit in SD1x18. error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18. error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18. error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18. error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD60x18. error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128. error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128. error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint256. error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40. error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x); /// @notice Thrown when trying to cast a UD60x18 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 { UD2x18 } from "./ValueType.sol"; /// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in SD1x18. error PRBMath_UD2x18_IntoSD1x18_Overflow(UD2x18 x); /// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in uint40. error PRBMath_UD2x18_IntoUint40_Overflow(UD2x18 x);
{ "remappings": [ "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/", "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/", "@prb/math/=lib/prb-math/src/", "ds-test/=lib/forge-std/lib/ds-test/src/", "forge-std/=lib/forge-std/src/", "upgrade-scripts/=lib/upgrade-scripts/src/", "UDS/=lib/upgrade-scripts/lib/UDS/src/", "@prb/test/=lib/prb-math/node_modules/@prb/test/", "futils/=lib/upgrade-scripts/lib/UDS/lib/futils/src/", "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/", "openzeppelin-contracts/=lib/openzeppelin-contracts/", "prb-math/=lib/prb-math/src/" ], "optimizer": { "enabled": true, "runs": 600 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "paris", "libraries": {} }
[{"inputs":[{"internalType":"contract FeeDistributor","name":"feeDistributor","type":"address"},{"internalType":"address","name":"admin","type":"address"},{"internalType":"address","name":"executor","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"BalancePriceLengthMismatch","type":"error"},{"inputs":[],"name":"CanOnlyBeFundedByParent","type":"error"},{"inputs":[],"name":"ConditionAlreadyPrepared","type":"error"},{"inputs":[],"name":"ConditionNotFound","type":"error"},{"inputs":[],"name":"ExcessiveCollateralDecimals","type":"error"},{"inputs":[],"name":"ExcessiveFunding","type":"error"},{"inputs":[],"name":"FeesConsumeInvestment","type":"error"},{"inputs":[],"name":"FeesExceedCollected","type":"error"},{"inputs":[],"name":"FeesExceedReserves","type":"error"},{"inputs":[],"name":"InvalidAmount","type":"error"},{"inputs":[],"name":"InvalidBurnAmount","type":"error"},{"inputs":[{"internalType":"address","name":"conditionOracle","type":"address"}],"name":"InvalidConditionOracle","type":"error"},{"inputs":[],"name":"InvalidERC20","type":"error"},{"inputs":[],"name":"InvalidFee","type":"error"},{"inputs":[],"name":"InvalidFundingAmount","type":"error"},{"inputs":[],"name":"InvalidHaltTime","type":"error"},{"inputs":[],"name":"InvalidIndex","type":"error"},{"inputs":[],"name":"InvalidInvestmentAmount","type":"error"},{"inputs":[],"name":"InvalidOutcomeIndex","type":"error"},{"inputs":[],"name":"InvalidOutcomeSlotCountsArray","type":"error"},{"inputs":[],"name":"InvalidOutcomeSlotsAmount","type":"error"},{"inputs":[],"name":"InvalidPayoutArray","type":"error"},{"inputs":[],"name":"InvalidPrices","type":"error"},{"inputs":[],"name":"InvalidQuantities","type":"error"},{"inputs":[],"name":"InvalidReceiverAddress","type":"error"},{"inputs":[],"name":"InvalidReturnAmount","type":"error"},{"inputs":[],"name":"InvestmentDrainsPool","type":"error"},{"inputs":[],"name":"MarketHalted","type":"error"},{"inputs":[],"name":"MarketUndecided","type":"error"},{"inputs":[],"name":"MaximumSellAmountExceeded","type":"error"},{"inputs":[],"name":"MinimumBuyAmountNotReached","type":"error"},{"inputs":[],"name":"MustBeCalledByOracle","type":"error"},{"inputs":[],"name":"NoLiquidityAvailable","type":"error"},{"inputs":[],"name":"NoPositionsToRedeem","type":"error"},{"inputs":[],"name":"OperationNotSupported","type":"error"},{"inputs":[],"name":"PayoutAlreadyReported","type":"error"},{"inputs":[],"name":"PayoutsAreAllZero","type":"error"},{"inputs":[],"name":"PoolValueZero","type":"error"},{"inputs":[],"name":"ResultNotReceivedYet","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"creator","type":"address"},{"indexed":false,"internalType":"contract IMarketMakerV1","name":"marketMaker","type":"address"},{"indexed":true,"internalType":"contract IConditionalTokens","name":"conditionalTokens","type":"address"},{"indexed":true,"internalType":"contract IERC20","name":"collateralToken","type":"address"},{"indexed":false,"internalType":"ConditionID","name":"conditionId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"haltTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"}],"name":"MarketMakerCreation","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"EXECUTOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"checkAdmin","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"checkExecutor","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"fee","type":"uint256"},{"components":[{"internalType":"contract IConditionalTokensV1_2","name":"conditionalTokens","type":"address"},{"internalType":"contract IERC20Metadata","name":"collateralToken","type":"address"},{"internalType":"address","name":"parentPool","type":"address"},{"internalType":"address","name":"priceOracle","type":"address"},{"internalType":"address","name":"conditionOracle","type":"address"}],"internalType":"struct MarketAddressParams","name":"addresses","type":"tuple"},{"components":[{"internalType":"QuestionID","name":"questionId","type":"bytes32"},{"internalType":"uint256[]","name":"fairPriceDecimals","type":"uint256[]"},{"internalType":"uint128","name":"minPriceDecimal","type":"uint128"},{"internalType":"uint256","name":"haltTime","type":"uint256"}],"internalType":"struct IMarketFactory.PriceMarketParams","name":"params","type":"tuple"}],"name":"createMarket","outputs":[{"internalType":"contract IMarketMakerV1","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"fee","type":"uint256"},{"components":[{"internalType":"contract IConditionalTokensV1_2","name":"conditionalTokens","type":"address"},{"internalType":"contract IERC20Metadata","name":"collateralToken","type":"address"},{"internalType":"address","name":"parentPool","type":"address"},{"internalType":"address","name":"priceOracle","type":"address"},{"internalType":"address","name":"conditionOracle","type":"address"}],"internalType":"struct MarketAddressParams","name":"addresses","type":"tuple"},{"components":[{"internalType":"QuestionID","name":"questionId","type":"bytes32"},{"internalType":"bytes","name":"packedPrices","type":"bytes"},{"internalType":"uint32","name":"haltTime","type":"uint32"}],"internalType":"struct IMarketFactoryV1_2.PackedPriceMarketParams","name":"params","type":"tuple"}],"name":"createMarket","outputs":[{"internalType":"contract IMarketMakerV1","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"fee","type":"uint256"},{"components":[{"internalType":"contract IConditionalTokensV1_2","name":"conditionalTokens","type":"address"},{"internalType":"contract IERC20Metadata","name":"collateralToken","type":"address"},{"internalType":"address","name":"parentPool","type":"address"},{"internalType":"address","name":"priceOracle","type":"address"},{"internalType":"address","name":"conditionOracle","type":"address"}],"internalType":"struct MarketAddressParams","name":"addresses","type":"tuple"},{"components":[{"internalType":"QuestionID","name":"questionId","type":"bytes32"},{"internalType":"bytes","name":"packedPrices","type":"bytes"},{"internalType":"uint32","name":"haltTime","type":"uint32"}],"internalType":"struct IMarketFactoryV1_2.PackedPriceMarketParams","name":"params","type":"tuple"}],"name":"createMarketConcrete","outputs":[{"internalType":"contract MarketMaker","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"fee","type":"uint256"},{"components":[{"internalType":"contract IConditionalTokensV1_2","name":"conditionalTokens","type":"address"},{"internalType":"contract IERC20Metadata","name":"collateralToken","type":"address"},{"internalType":"address","name":"parentPool","type":"address"},{"internalType":"address","name":"priceOracle","type":"address"},{"internalType":"address","name":"conditionOracle","type":"address"}],"internalType":"struct MarketAddressParams","name":"addresses","type":"tuple"},{"internalType":"uint256","name":"legQuestionIdMask","type":"uint256"},{"components":[{"internalType":"QuestionID[]","name":"questionIds","type":"bytes32[]"},{"internalType":"uint256[]","name":"indices","type":"uint256[]"},{"internalType":"uint256[]","name":"outcomeSlotCounts","type":"uint256[]"}],"internalType":"struct ParlayLegs","name":"legs","type":"tuple"}],"name":"createParlayMarket","outputs":[{"internalType":"contract IMarketMakerV1_2","name":"marketMaker","type":"address"},{"internalType":"QuestionID","name":"parlayQuestionId","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"fee","type":"uint256"},{"components":[{"internalType":"contract IConditionalTokensV1_2","name":"conditionalTokens","type":"address"},{"internalType":"contract IERC20Metadata","name":"collateralToken","type":"address"},{"internalType":"address","name":"parentPool","type":"address"},{"internalType":"address","name":"priceOracle","type":"address"},{"internalType":"address","name":"conditionOracle","type":"address"}],"internalType":"struct MarketAddressParams","name":"addresses","type":"tuple"},{"internalType":"uint256","name":"legQuestionIdMask","type":"uint256"},{"components":[{"internalType":"QuestionID[]","name":"questionIds","type":"bytes32[]"},{"internalType":"uint256[]","name":"indices","type":"uint256[]"},{"internalType":"uint256[]","name":"outcomeSlotCounts","type":"uint256[]"}],"internalType":"struct ParlayLegs","name":"legs","type":"tuple"}],"name":"createParlayMarketConcrete","outputs":[{"internalType":"contract MarketMaker","name":"","type":"address"},{"internalType":"QuestionID","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IConditionalTokensV1_2","name":"conditionalTokens","type":"address"},{"internalType":"contract IERC20Metadata","name":"collateralToken","type":"address"},{"internalType":"address","name":"parentPool","type":"address"},{"internalType":"address","name":"priceOracle","type":"address"},{"internalType":"address","name":"conditionOracle","type":"address"}],"internalType":"struct MarketAddressParams","name":"addresses","type":"tuple"},{"internalType":"ConditionID","name":"conditionId","type":"bytes32"}],"name":"predictMarketAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"}]
Contract Creation Code
60a06040523480156200001157600080fd5b50604051620080c7380380620080c78339810160408190526200003491620004d0565b826040516200004390620004a9565b6001600160a01b039091168152602001604051809103906000f08015801562000070573d6000803e3d6000fd5b506001600160a01b031660805262000089828262000092565b50505062000524565b600054610100900460ff1615808015620000b35750600054600160ff909116105b80620000cf5750303b158015620000cf575060005460ff166001145b620001385760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084015b60405180910390fd5b6000805460ff1916600117905580156200015c576000805461ff0019166101001790555b620001688383620001b4565b8015620001af576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050565b600054610100900460ff16620002105760405162461bcd60e51b815260206004820152602b6024820152600080516020620080a783398151915260448201526a6e697469616c697a696e6760a81b60648201526084016200012f565b6200021a62000234565b6200022462000292565b620002308282620002f8565b5050565b600054610100900460ff16620002905760405162461bcd60e51b815260206004820152602b6024820152600080516020620080a783398151915260448201526a6e697469616c697a696e6760a81b60648201526084016200012f565b565b600054610100900460ff16620002ee5760405162461bcd60e51b815260206004820152602b6024820152600080516020620080a783398151915260448201526a6e697469616c697a696e6760a81b60648201526084016200012f565b620002906200039d565b600054610100900460ff16620003545760405162461bcd60e51b815260206004820152602b6024820152600080516020620080a783398151915260448201526a6e697469616c697a696e6760a81b60648201526084016200012f565b6200036160008362000405565b6001600160a01b038116156200023057620002307fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e638262000405565b600054610100900460ff16620003f95760405162461bcd60e51b815260206004820152602b6024820152600080516020620080a783398151915260448201526a6e697469616c697a696e6760a81b60648201526084016200012f565b6097805460ff19169055565b60008281526065602090815260408083206001600160a01b038516845290915290205460ff16620002305760008281526065602090815260408083206001600160a01b03851684529091529020805460ff19166001179055620004653390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6161528062001f5583390190565b6001600160a01b0381168114620004cd57600080fd5b50565b600080600060608486031215620004e657600080fd5b8351620004f381620004b7565b60208501519093506200050681620004b7565b60408501519092506200051981620004b7565b809150509250925092565b608051611a076200054e600039600081816107c3015281816109c90152610a110152611a076000f3fe608060405234801561001057600080fd5b50600436106101515760003560e01c80635c975abb116100cd578063a217fddf11610081578063b4b1516711610066578063b4b1516714610303578063d547741f14610316578063e0578fce1461032957600080fd5b8063a217fddf146102e8578063aecc550a146102f057600080fd5b80638456cb59116100b25780638456cb59146102945780639026dee81461029c57806391d14854146102af57600080fd5b80635c975abb1461027657806383edf3171461028157600080fd5b80632a2d1c1b1161012457806336568abe1161010957806336568abe146102485780633f4ba83a1461025b5780634a1097c71461026357600080fd5b80632a2d1c1b146102085780632f2ff15d1461023357600080fd5b806301ffc9a71461015657806307bd02651461017e57806318ea084f146101b3578063248a9ca3146101e5575b600080fd5b6101696101643660046111a8565b61033c565b60405190151581526020015b60405180910390f35b6101a57fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e6381565b604051908152602001610175565b6101c66101c13660046111ea565b61039d565b604080516001600160a01b039093168352602083019190915201610175565b6101a56101f3366004611252565b60009081526065602052604090206001015490565b61021b610216366004611317565b6103be565b6040516001600160a01b039091168152602001610175565b610246610241366004611422565b6103d3565b005b610246610256366004611422565b6103fd565b61024661048e565b6101c66102713660046111ea565b6104a1565b60975460ff16610169565b61024661028f366004611452565b610553565b610246610580565b6102466102aa366004611452565b610591565b6101696102bd366004611422565b60009182526065602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6101a5600081565b61021b6102fe36600461148f565b61059c565b61021b610311366004611317565b61061d565b610246610324366004611422565b61078a565b61021b6103373660046115a1565b6107af565b60006001600160e01b031982166357662a8560e11b148061036d57506001600160e01b0319821663b4b1516760e01b145b8061038857506001600160e01b03198216634a1097c760e01b145b806103975750610397826107e8565b92915050565b6000806000806103af888888886104a1565b90999098509650505050505050565b60006103cb84848461061d565b949350505050565b6000828152606560205260409020600101546103ee8161081d565b6103f88383610827565b505050565b6001600160a01b03811633146104805760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201527f20726f6c657320666f722073656c66000000000000000000000000000000000060648201526084015b60405180910390fd5b61048a82826108c9565b5050565b61049733610591565b61049f61094c565b565b600080806104b26020870187611452565b6001600160a01b031663289ab7e26104d060a0890160808a01611452565b87876040518463ffffffff1660e01b81526004016104f093929190611667565b60408051808303816000875af115801561050e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105329190611721565b909250905061054787878363ffffffff61099e565b92505094509492505050565b61057d7fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e6382610b52565b50565b61058933610591565b61049f610bc7565b61057d600082610b52565b600063ffffffff8016826060015111156105c957604051635ec5096760e11b815260040160405180910390fd5b60006040518060600160405280846000015181526020016105f48560200151655af3107a4000610c04565b8152602001846060015163ffffffff16815250905061061485858361061d565b95945050505050565b600061062833610553565b60006106378360200151610cb9565b61064290600161175b565b9050600181116106655760405163104272fb60e11b815260040160405180910390fd5b61068f633eafa4fd60e11b61068060a0870160808801611452565b6001600160a01b031690610cc9565b6106c8576106a360a0850160808601611452565b60405163c5a5657d60e01b81526001600160a01b039091166004820152602401610477565b60006106da60a0860160808701611452565b905060006001600160a01b038216630e8a8cf36106fa6020890189611452565b87600001518689602001518a604001516040518663ffffffff1660e01b815260040161072a9594939291906117be565b6020604051808303816000875af1158015610749573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061076d9190611804565b905061077f878783886040015161099e565b979650505050505050565b6000828152606560205260409020600101546107a58161081d565b6103f883836108c9565b6000806107bc8484610cec565b90506103cb7f000000000000000000000000000000000000000000000000000000000000000082610d7e565b60006001600160e01b03198216637965db0b60e01b148061039757506301ffc9a760e01b6001600160e01b0319831614610397565b61057d8133610b52565b60008281526065602090815260408083206001600160a01b038516845290915290205460ff1661048a5760008281526065602090815260408083206001600160a01b03851684529091529020805460ff191660011790556108853390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60008281526065602090815260408083206001600160a01b038516845290915290205460ff161561048a5760008281526065602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b610954610dde565b6097805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b6000806109ab8585610cec565b604080518082019091528581526020810188905290915060006109ee7f000000000000000000000000000000000000000000000000000000000000000084610d7e565b90506001600160a01b0381163b15610a0a5792506103cb915050565b6000610a367f000000000000000000000000000000000000000000000000000000000000000085610e30565b9050816001600160a01b0316816001600160a01b031614610a5957610a5961181d565b81610a6a60408a0160208b01611452565b6001600160a01b0316610a8060208b018b611452565b8551602080880151604080516001600160a01b0388811682529381019490945263ffffffff8d16908401526060830152919091169033907f2d357fefe8d7e1012a0782310cc7c7c6670f306a0d1e035815e27c11a5ea8c879060800160405180910390a460405163ae3afc0360e01b81526001600160a01b0382169063ae3afc0390610b12908c908890600401611833565b600060405180830381600087803b158015610b2c57600080fd5b505af1158015610b40573d6000803e3d6000fd5b50929c9b505050505050505050505050565b60008281526065602090815260408083206001600160a01b038516845290915290205460ff1661048a57610b8581610ecd565b610b90836020610edf565b604051602001610ba19291906118c1565b60408051601f198184030181529082905262461bcd60e51b825261047791600401611942565b610bcf611088565b6097805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586109813390565b81516060906002810267ffffffffffffffff811115610c2557610c2561126b565b6040519080825280601f01601f191660200182016040528015610c4f576020820181803683370190505b50915060005b81811015610cb157600084868381518110610c7257610c72611955565b602002602001015181610c8757610c8761196b565b04905061ffff811115610c9c57610c9c61181d565b60f01b60028202840160200152600101610c55565b505092915050565b6000600282516103979190611981565b6000610cd4836110db565b8015610ce55750610ce5838361110e565b9392505050565b6000610cfb6020840184611452565b610d0b6040850160208601611452565b610d1b6060860160408701611452565b610d2b60a0870160808801611452565b604080516001600160a01b039586166020820152938516908401529083166060830152909116608082015260a0810183905260c00160405160208183030381529060405280519060200120905092915050565b6040513060388201526f5af43d82803e903d91602b57fd5bf3ff602482015260148101839052733d602d80600a3d3981f3363d3d373d3d3d363d738152605881018290526037600c82012060788201526055604390910120600090610ce5565b60975460ff1661049f5760405162461bcd60e51b815260206004820152601460248201527f5061757361626c653a206e6f74207061757365640000000000000000000000006044820152606401610477565b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b1760205281603760096000f590506001600160a01b0381166103975760405162461bcd60e51b815260206004820152601760248201527f455243313136373a2063726561746532206661696c65640000000000000000006044820152606401610477565b60606103976001600160a01b03831660145b60606000610eee8360026119a3565b610ef990600261175b565b67ffffffffffffffff811115610f1157610f1161126b565b6040519080825280601f01601f191660200182016040528015610f3b576020820181803683370190505b509050600360fc1b81600081518110610f5657610f56611955565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110610f8557610f85611955565b60200101906001600160f81b031916908160001a9053506000610fa98460026119a3565b610fb490600161175b565b90505b6001811115611039577f303132333435363738396162636465660000000000000000000000000000000085600f1660108110610ff557610ff5611955565b1a60f81b82828151811061100b5761100b611955565b60200101906001600160f81b031916908160001a90535060049490941c93611032816119ba565b9050610fb7565b508315610ce55760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610477565b60975460ff161561049f5760405162461bcd60e51b815260206004820152601060248201527f5061757361626c653a20706175736564000000000000000000000000000000006044820152606401610477565b60006110ee826301ffc9a760e01b61110e565b80156103975750611107826001600160e01b031961110e565b1592915050565b604080516001600160e01b03198316602480830191909152825180830390910181526044909101909152602080820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166301ffc9a760e01b178152825160009392849283928392918391908a617530fa92503d91506000519050828015611195575060208210155b801561077f575015159695505050505050565b6000602082840312156111ba57600080fd5b81356001600160e01b031981168114610ce557600080fd5b600060a082840312156111e457600080fd5b50919050565b600080600080610100858703121561120157600080fd5b8435935061121286602087016111d2565b925060c0850135915060e085013567ffffffffffffffff81111561123557600080fd5b85016060818803121561124757600080fd5b939692955090935050565b60006020828403121561126457600080fd5b5035919050565b634e487b7160e01b600052604160045260246000fd5b6040516060810167ffffffffffffffff811182821017156112a4576112a461126b565b60405290565b6040516080810167ffffffffffffffff811182821017156112a4576112a461126b565b604051601f8201601f1916810167ffffffffffffffff811182821017156112f6576112f661126b565b604052919050565b803563ffffffff8116811461131257600080fd5b919050565b600080600060e0848603121561132c57600080fd5b83359250602061133e868287016111d2565b925060c085013567ffffffffffffffff8082111561135b57600080fd5b908601906060828903121561136f57600080fd5b611377611281565b82358152838301358281111561138c57600080fd5b8301601f81018a1361139d57600080fd5b8035838111156113af576113af61126b565b6113c1601f8201601f191687016112cd565b93508084528a868284010111156113d757600080fd5b80868301878601376000868286010152505081848201526113fa604084016112fe565b6040820152809450505050509250925092565b6001600160a01b038116811461057d57600080fd5b6000806040838503121561143557600080fd5b8235915060208301356114478161140d565b809150509250929050565b60006020828403121561146457600080fd5b8135610ce58161140d565b80356fffffffffffffffffffffffffffffffff8116811461131257600080fd5b600080600060e084860312156114a457600080fd5b8335925060206114b6868287016111d2565b925060c085013567ffffffffffffffff808211156114d357600080fd5b90860190608082890312156114e757600080fd5b6114ef6112aa565b82358152838301358281111561150457600080fd5b8301601f81018a1361151557600080fd5b8035838111156115275761152761126b565b8060051b93506115388685016112cd565b818152938201860193868101908c86111561155257600080fd5b928701925b8584101561157057833582529287019290870190611557565b84880152506115849150506040840161146f565b604082015260608301356060820152809450505050509250925092565b60008060c083850312156115b457600080fd5b6115be84846111d2565b9460a0939093013593505050565b6000808335601e198436030181126115e357600080fd5b830160208101925035905067ffffffffffffffff81111561160357600080fd5b8060051b360382131561161557600080fd5b9250929050565b81835260007f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83111561164e57600080fd5b8260051b80836020870137939093016020019392505050565b6001600160a01b03841681526000602084818401526060604084015260c0830161169185866115cc565b606086810152918290529060009060e086015b818310156116c25783358152928401926001929092019184016116a4565b6116ce858901896115cc565b95509350605f199250828782030160808801526116ec81868661161c565b945050506116fd60408701876115cc565b9250818685030160a087015261171484848361161c565b9998505050505050505050565b6000806040838503121561173457600080fd5b505080516020909101519092909150565b634e487b7160e01b600052601160045260246000fd5b8082018082111561039757610397611745565b60005b83811015611789578181015183820152602001611771565b50506000910152565b600081518084526117aa81602086016020860161176e565b601f01601f19169290920160200192915050565b6001600160a01b038616815284602082015283604082015260a0606082015260006117ec60a0830185611792565b905063ffffffff831660808301529695505050505050565b60006020828403121561181657600080fd5b5051919050565b634e487b7160e01b600052600160045260246000fd5b60e0810183356118428161140d565b6001600160a01b03908116835260208501359061185e8261140d565b90811660208401526040850135906118758261140d565b908116604084015260608501359061188c8261140d565b90811660608401526080850135906118a38261140d565b166080830152825160a083015260209092015160c090910152919050565b7f416363657373436f6e74726f6c3a206163636f756e74200000000000000000008152600083516118f981601785016020880161176e565b7f206973206d697373696e6720726f6c6520000000000000000000000000000000601791840191820152835161193681602884016020880161176e565b01602801949350505050565b602081526000610ce56020830184611792565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601260045260246000fd5b60008261199e57634e487b7160e01b600052601260045260246000fd5b500490565b808202811582820484141761039757610397611745565b6000816119c9576119c9611745565b50600019019056fea2646970667358221220f9f5d2a0daf41405fba8c292024aae140959da94319ead270aa72484a372ad4264736f6c6343000813003360a06040523480156200001157600080fd5b506040516200615238038062006152833981016040819052620000349162000114565b6001600160a01b0381166080526200004b62000052565b5062000146565b600054610100900460ff1615620000bf5760405162461bcd60e51b815260206004820152602760248201527f496e697469616c697a61626c653a20636f6e747261637420697320696e697469604482015266616c697a696e6760c81b606482015260840160405180910390fd5b60005460ff908116101562000112576000805460ff191660ff9081179091556040519081527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b565b6000602082840312156200012757600080fd5b81516001600160a01b03811681146200013f57600080fd5b9392505050565b608051615fe2620001706000396000818161273e01528181612a2b0152612ac30152615fe26000f3fe608060405234801561001057600080fd5b506004361061032b5760003560e01c806372441d54116101b2578063b2016bd4116100f9578063d2da4040116100a2578063e03031a61161007c578063e03031a6146106fc578063eb175b7e1461071d578063f23a6e6114610733578063f55c79d01461074657600080fd5b8063d2da40401461069f578063d3c9727c146106b0578063dd62ed3e146106c357600080fd5b8063bc197c81116100d3578063bc197c8114610658578063c7ff158414610684578063cc071c4f1461068c57600080fd5b8063b2016bd414610624578063b518d9a414610637578063b78d05f71461064a57600080fd5b80639003adfe1161015b578063a457c2d711610135578063a457c2d7146105eb578063a9059cbb146105fe578063ae3afc031461061157600080fd5b80639003adfe146105b957806395d89b41146105c25780639f2a2944146105ca57600080fd5b80637e11b31f1161018c5780637e11b31f146105625780638ab0c0b2146105905780638ac2c6801461059857600080fd5b806372441d541461051e57806375172a8b14610547578063792052181461054f57600080fd5b8063395093511161027657806352375bb11161021f5780635d5d4613116101f95780635d5d4613146104da578063702fa158146104ed57806370a08231146104f557600080fd5b806352375bb11461049357806354147e9e1461049b5780635bd9e299146104ae57600080fd5b8063429c9dff11610250578063429c9dff146104455780634343116a14610458578063480fa82e1461046b57600080fd5b806339509351146103fb5780633c3ad82e1461040e57806340993b261461042357600080fd5b806318160ddd116102d85780632ddc7de7116102b25780632ddc7de7146103da578063313ce567146103e45780633706c4da146103f357600080fd5b806318160ddd146103b75780631ba2f531146103bf57806323b872dd146103c757600080fd5b80630b1af86a116103095780630b1af86a14610380578063164e68de1461039557806316dbd7761461039557600080fd5b806301ffc9a71461033057806306fdde0314610358578063095ea7b31461036d575b600080fd5b61034361033e366004615254565b610759565b60405190151581526020015b60405180910390f35b6103606107f0565b60405161034f91906152a2565b61034361037b3660046152ea565b610882565b61038861089a565b60405161034f9190615351565b6103a96103a3366004615364565b50600090565b60405190815260200161034f565b609a546103a9565b6103a96108ca565b6103436103d5366004615381565b61096e565b6103a96101015481565b6040516012815260200161034f565b60cd546103a9565b6103436104093660046152ea565b610994565b61042161041c36600461540e565b6109d3565b005b610436610431366004615450565b6109ec565b60405161034f9392919061547c565b610436610453366004615450565b610a0f565b6103a961046636600461549b565b610a44565b61047e61047936600461540e565b610a5f565b6040805192835260208301919091520161034f565b610388610b10565b6103a96104a93660046154bd565b610ba2565b610100546104c2906001600160a01b031681565b6040516001600160a01b03909116815260200161034f565b6103a96104e83660046154bd565b610c2e565b610388610c3a565b6103a9610503366004615364565b6001600160a01b031660009081526098602052604090205490565b6103a961052c366004615364565b6001600160a01b0316600090815260cc602052604090205490565b6103a9610c72565b61043661055d3660046154d6565b610d03565b610102546105779067ffffffffffffffff1681565b60405167ffffffffffffffff909116815260200161034f565b6103a9610ff0565b610102546105779068010000000000000000900467ffffffffffffffff1681565b6103a960cb5481565b610360610fff565b6105dd6105d83660046152ea565b61100e565b60405161034f929190615522565b6103436105f93660046152ea565b611327565b61034361060c3660046152ea565b6113c9565b61042161061f366004615544565b6113d7565b60ca546104c2906001600160a01b031681565b6103a96106453660046152ea565b6117b2565b61042161041c366004615589565b61066b610666366004615701565b61181a565b6040516001600160e01b0319909116815260200161034f565b61034361187b565b61043661069a3660046157af565b6118ef565b6097546001600160a01b03166104c2565b6103a96106be366004615450565b611913565b6103a96106d13660046157ea565b6001600160a01b03918216600090815260996020908152604080832093909416825291909152205490565b61070f61070a3660046154bd565b61195c565b60405161034f929190615823565b610725611975565b60405161034f92919061583c565b61066b6107413660046158b8565b611b36565b61043661075436600461549b565b611b77565b60006001600160e01b031982166319a298e760e01b148061078a57506001600160e01b0319821663034b690160e61b145b806107a557506001600160e01b031982166306e253b560e11b145b806107c057506001600160e01b03198216635ee02cbf60e01b145b806107db57506001600160e01b03198216633bbccfe760e01b145b806107ea57506107ea82611b95565b92915050565b6060609b80546107ff90615921565b80601f016020809104026020016040519081016040528092919081815260200182805461082b90615921565b80156108785780601f1061084d57610100808354040283529160200191610878565b820191906000526020600020905b81548152906001019060200180831161085b57829003601f168201915b5050505050905090565b600033610890818585611bca565b5060019392505050565b60606000806108a7611975565b915091506108c382600001518360200151846040015184611cee565b9250505090565b6101005460ca546101015460405163071b3a2360e41b81523060048201526001600160a01b0392831660248201526044810191909152600092839283929116906371b3a23090606401600060405180830381865afa158015610930573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261095891908101906159b6565b915091506108c38282610969610c72565b611ed2565b60003361097c858285611ef1565b610987858585611f83565b60019150505b9392505050565b3360008181526099602090815260408083206001600160a01b038716845290915281205490919061089090829086906109ce908790615a30565b611bca565b6040516329a270f560e01b815260040160405180910390fd5b6000806060610a0033878787600080610d03565b92509250925093509350939050565b6000806060600080610a1f611975565b91509150610a308888888585612134565b50929b909a50919850909650505050505050565b60006040516329a270f560e01b815260040160405180910390fd5b60008060005b83811015610b08576000858583818110610a8157610a81615a43565b9050602002016020810190610a969190615364565b90506000610ab9826001600160a01b031660009081526098602052604090205490565b905080600003610aca575050610af6565b6000610ad6838361100e565b9150610ae490508186615a30565b9450610af08287615a30565b95505050505b80610b0081615a59565b915050610a65565b509250929050565b6101005460ca5461010154604051633026b36f60e11b81523060048201526001600160a01b0392831660248201526044810191909152606092919091169063604d66de906064015b600060405180830381865afa158015610b75573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610b9d9190810190615a72565b905090565b60ca546101015460408051602080820193909352808201859052815180820383018152606090910190915280519101206000916107ea916001600160a01b03909116905b6040516bffffffffffffffffffffffff19606084901b1660208201526034810182905260009060540160408051601f1981840301815291905280516020909101209392505050565b60006107ea33836117b2565b610100546101015460405163fbdd125560e01b815260048101919091526060916001600160a01b03169063fbdd125590602401610b58565b60ca546040516370a0823160e01b815230600482015260009182916001600160a01b03909116906370a0823190602401602060405180830381865afa158015610cbf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ce39190615aa7565b60cb5490915080821015610cf957610cf9615ac0565b6108c38183615ad6565b6000806060610d1061187b565b15610d2e576040516323fa277f60e21b815260040160405180910390fd5b6101025468010000000000000000900467ffffffffffffffff16881015610d6857604051631bf1f55760e11b815260040160405180910390fd5b600080610d8f60405180606001604052806000815260200160008152602001600081525090565b600080610d9a611975565b91509150610da7826122a3565b9350610db68d8d8c8585612134565b939b50909950975095509250505088861015610de55760405163592d015360e01b815260040160405180910390fd5b610dee816122b2565b610e063360ca546001600160a01b031690308e6123a9565b610e108588612414565b8215610e1f57610e1f8361244b565b610100546001600160a01b031663f242432a308e610e3c8e610ba2565b6040516001600160e01b031960e086901b1681526001600160a01b03938416600482015292909116602483015260448201526064810189905260a06084820152600060a482015260c401600060405180830381600087803b158015610ea057600080fd5b505af1158015610eb4573d6000803e3d6000fd5b5050610100546001600160a01b0316915063f242432a9050308e610ed786610ba2565b6040516001600160e01b031960e086901b1681526001600160a01b0393841660048201529290911660248301526044820152606481018e905260a06084820152600060a482015260c401600060405180830381600087803b158015610f3b57600080fd5b505af1158015610f4f573d6000803e3d6000fd5b50505050610f5c816124e1565b604080518c8152602081018790529081018790528a906001600160a01b038e16907f64cc4fe16c02ad83cc7cef979438c326a32c6984201d43cc67efb86ba07c7e8b9060600160405180910390a37fd16db9df479b59fe65c1ac1cf7b45b12b0b432fe457d316acdcbe22356ea495484604051610fd99190615351565b60405180910390a150505096509650969350505050565b610ffc6012600a615bc5565b81565b6060609c80546107ff90615921565b610100546101015460405163de61ece160e01b81526060926000926001600160a01b039091169163de61ece19161104b9160040190815260200190565b602060405180830381865afa158015611068573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061108c9190615bd1565b6110a95760405163d1d695db60e01b815260040160405180910390fd5b60008060006110b6612671565b9250925092506110d28160cb546110cd9190615ad6565b6128a8565b6110db866128e5565b955093506110e98787612924565b8451806110f8576110f8615ac0565b60008167ffffffffffffffff811115611113576111136155bb565b60405190808252806020026020018201604052801561113c578160200160208202803683370190505b50905060005b8281101561117a578082828151811061115d5761115d615a43565b60209081029190910101528061117281615a59565b915050611142565b5085156111985760ca54611198906001600160a01b03168a886129cb565b6101005460ca546101015460405163c87e500960e01b81526001600160a01b039384169363c87e5009936111d9938f93929091169187908e90600401615bf3565b6020604051808303816000875af11580156111f8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061121c9190615aa7565b6112269087615a30565b95506112338585856129fb565b60006112476097546001600160a01b031690565b9050806001600160a01b03168a6001600160a01b0316036112c45760405163d77eb4c760e01b815260048101889052602481018a90526001600160a01b0382169063d77eb4c790604401600060405180830381600087803b1580156112ab57600080fd5b505af11580156112bf573d6000803e3d6000fd5b505050505b60408051600081526020810191829052906001600160a01b038c16907f96bd1544577eb6c104cdc0a1e4eda89c64f8875c006dfda5baaef1aa5628b4b990611311908b9085908f90615c37565b60405180910390a2505050505050509250929050565b3360008181526099602090815260408083206001600160a01b0387168452909152812054909190838110156113b15760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084015b60405180910390fd5b6113be8286868403611bca565b506001949350505050565b600033610890818585611f83565b600054610100900460ff16158080156113f75750600054600160ff909116105b806114115750303b158015611411575060005460ff166001145b6114835760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201527f647920696e697469616c697a656400000000000000000000000000000000000060648201526084016113a8565b6000805460ff1916600117905580156114a6576000805461ff0019166101001790555b60006114b86060850160408601615364565b6001600160a01b0316036114fb576114d66060840160408501615364565b6040516320d6c2ad60e01b81526001600160a01b0390911660048201526024016113a8565b61151361150e6060850160408601615364565b612b37565b61152b6115266040850160208601615364565b612bae565b611533612c4a565b6115406020840184615364565b61010080546001600160a01b0319166001600160a01b039290921691909117905581356101015561156f61187b565b1561158d576040516323fa277f60e21b815260040160405180910390fd5b60ca546040805163313ce56760e01b815290516000926001600160a01b03169163313ce5679160048083019260209291908290030181865afa1580156115d7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115fb9190615c60565b60ff169050600061160d82600a615bc5565b905067ffffffffffffffff8110611637576040516347aad2ef60e11b815260040160405180910390fd5b8084602001351061165b576040516358d620b360e01b815260040160405180910390fd5b600060208501351561169957611675826020870135612cb7565b90506000611687602087013583615c83565b1161169457611694615ac0565b61169d565b5060015b67ffffffffffffffff6116b26012600a615bc5565b11156116c0576116c0615ac0565b600060128410156116f6576116d6846012615ad6565b6116e190600a615bc5565b6116ef906020880135615c83565b905061172a565b60128411156117235761170a601285615ad6565b61171590600a615bc5565b6116ef906020880135615cb0565b5060208501355b610102805467ffffffffffffffff84811668010000000000000000026fffffffffffffffffffffffffffffffff1990921690841617178155505050505080156117ad576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050565b60006117bc61187b565b156117da576040516323fa277f60e21b815260040160405180910390fd5b6097546001600160a01b0384811691161461180857604051633642e25360e21b815260040160405180910390fd5b61098d83836118156108ca565b612cee565b60006001600160a01b0386163014801561183b57506001600160a01b038516155b801561185b5750610100546001600160a01b0316336001600160a01b0316145b1561186e575063bc197c8160e01b611872565b5060005b95945050505050565b6101005461010154604051637cf15c8960e11b815260048101919091526000916001600160a01b03169063f9e2b91290602401602060405180830381865afa1580156118cb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b9d9190615bd1565b600080606061190387878787600080610d03565b9250925092509450945094915050565b600061191d61187b565b1561193b576040516323fa277f60e21b815260040160405180910390fd5b836000036109d357604051637f28d71160e01b815260040160405180910390fd5b600060603361196b8185612e8c565b9250925050915091565b61199960405180606001604052806000815260200160008152602001606081525090565b6101005460ca546101015460405163071b3a2360e41b81523060048201526001600160a01b0392831660248201526044810191909152606092839216906371b3a23090606401600060405180830381865afa1580156119fc573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052611a2491908101906159b6565b8051909350909150611a37906001615a30565b815114611a4657611a46615ac0565b6040518060600160405280611a5a60cd5490565b8152602001600081526020018281525092506000611a806097546001600160a01b031690565b90506001600160a01b03811615611b3057604051639093708360e01b815230600482015260009081906001600160a01b038416906390937083906024016040805180830381865afa158015611ad9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611afd9190615cc4565b915091508086600001818151611b139190615a30565b905250602086018051839190611b2a908390615a30565b90525050505b50509091565b60006001600160a01b03861630148015611b645750610100546001600160a01b0316336001600160a01b0316145b1561186e575063f23a6e6160e01b611872565b6000806060611b8885856000610a0f565b9250925092509250925092565b60006001600160e01b03198216630271189760e51b14806107ea57506301ffc9a760e01b6001600160e01b03198316146107ea565b6001600160a01b038316611c2c5760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b60648201526084016113a8565b6001600160a01b038216611c8d5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b60648201526084016113a8565b6001600160a01b0383811660008181526099602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6060825182511115611d135760405163c57d332960e01b815260040160405180910390fd5b84600003611d3457604051636cdaa7bb60e01b815260040160405180910390fd5b815167ffffffffffffffff811115611d4e57611d4e6155bb565b604051908082528060200260200182016040528015611d77578160200160208202803683370190505b5090506000611d886012600a615bc5565b905060005b8251811015611ec857600086868381518110611dab57611dab615a43565b6020026020010151611dbd9190615a30565b90506000805b8651811015611e2f57838114611e1d57611e1085888381518110611de957611de9615a43565b6020026020010151898781518110611e0357611e03615a43565b602002602001015161301f565b611e1a9083615a30565b91505b80611e2781615a59565b915050611dc3565b506000611e54878581518110611e4757611e47615a43565b6020026020010151613045565b9050611e6283838c846131cb565b91506000611e708684615a30565b905080611e7f6012600a615bc5565b611e899088615c83565b611e939190615cb0565b878681518110611ea557611ea5615a43565b602002602001018181525050505050508080611ec090615a59565b915050611d8d565b5050949350505050565b600081611edf8585613265565b611ee99190615a30565b949350505050565b6001600160a01b038381166000908152609960209081526040808320938616835292905220546000198114611f7d5781811015611f705760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e636500000060448201526064016113a8565b611f7d8484848403611bca565b50505050565b6001600160a01b038316611fe75760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b60648201526084016113a8565b6001600160a01b0382166120495760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b60648201526084016113a8565b6001600160a01b038316600090815260986020526040902054818110156120c15760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b60648201526084016113a8565b6001600160a01b0380851660008181526098602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906121219086815260200190565b60405180910390a3611f7d848484613325565b6000806000606061215f60405180606001604052806000815260200160008152602001600081525090565b61216b6012600a615bc5565b61010254612184908a9067ffffffffffffffff16615a30565b61218e908c615c83565b6121989190615cb0565b92508983106121ba57604051634c86529b60e01b815260040160405180910390fd5b60006121c6848c615ad6565b90506000806121e5838d8c600001518d602001518e604001518e613359565b91509150600060405180608001604052808581526020018481526020018381526020018f815250905060006122226097546001600160a01b031690565b90506000612245826001600160a01b031660009081526098602052604090205490565b9050612250609a5490565b811461225e5761225e615ac0565b61226a8f828f866135a0565b809950819c50829d5050505061228e8d600001518e602001518f604001518f611cee565b97505050505050509550955095509550959050565b60006107ea82604001516137be565b60006122c66097546001600160a01b031690565b8251909150156123a5576020820151156122e2576122e2615ac0565b6040820151156122f4576122f4615ac0565b6001600160a01b03811661230a5761230a615ac0565b8151604051635cd9ef8160e01b81526000916001600160a01b03841691635cd9ef819161233d9160040190815260200190565b60408051808303816000875af115801561235b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061237f9190615cc4565b5083519091508110156117ad5760405163980427cb60e01b815260040160405180910390fd5b5050565b6040516001600160a01b0380851660248301528316604482015260648101829052611f7d9085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526137ce565b61241d826138a0565b80156123a5576000818152610103602052604081208054849290612442908490615a30565b90915550505050565b6101005460ca54612469916001600160a01b03918216911683613920565b6101005460ca5461010154604051636e8a12b160e11b81526001600160a01b03928316600482015260248101919091526044810184905291169063dd14256290606401600060405180830381600087803b1580156124c657600080fd5b505af11580156124da573d6000803e3d6000fd5b5050505050565b60006124f56097546001600160a01b031690565b905060008260400151118061250e575060008260200151115b156123a55781511561252257612522615ac0565b6001600160a01b03811661253857612538615ac0565b60408201511561255057612550818360400151612924565b60208201511561257957602082015160ca54612579916001600160a01b039091169083906129cb565b6020820151604080840151905163d77eb4c760e01b81526001600160a01b0384169263d77eb4c7926125b692600401918252602082015260400190565b600060405180830381600087803b1580156125d057600080fd5b505af11580156125e4573d6000803e3d6000fd5b50600092508291506125f39050565b60405190808252806020026020018201604052801561261c578160200160208202803683370190505b509050816001600160a01b03167f96bd1544577eb6c104cdc0a1e4eda89c64f8875c006dfda5baaef1aa5628b4b9846020015183866040015160405161266493929190615c37565b60405180910390a2505050565b60608060008060cb5490508060000361268a5750909192565b6101005461010154604051631aa94e1d60e31b815260048101919091526000916001600160a01b03169063d54a70e890602401600060405180830381865afa1580156126da573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526127029190810190615ce8565b5090506000612710826137be565b9050600082828151811061272657612726615a43565b6020026020010151111561273c57505050909192565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663970006006040518163ffffffff1660e01b8152600401600060405180830381865afa15801561279a573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526127c29190810190615d2f565b9550855167ffffffffffffffff8111156127de576127de6155bb565b604051908082528060200260200182016040528015612807578160200160208202803683370190505b5094506000935060005b865181101561289f57600087828151811061282e5761282e615a43565b60200260200101519050600061010360008381526020019081526020016000205490508060000361286057505061288d565b8088848151811061287357612873615a43565b60209081029190910101526128888188615a30565b965050505b8061289781615a59565b915050612811565b50505050909192565b60cb548111156128cb5760405163cd45232960e01b815260040160405180910390fd5b8060cb60008282546128dd9190615ad6565b909155505050565b6000606060006128f4609a5490565b90506129088482612903610c72565b613a3c565b925061291c8482612917610b10565b613a70565b915050915091565b80600003612945576040516302075cc160e41b815260040160405180910390fd5b6001600160a01b03821660009081526098602090815260408083205460cc90925282205461297591908490613b52565b6001600160a01b038416600090815260cc60205260408120805492935083929091906129a2908490615ad6565b925050819055508060cd60008282546129bb9190615ad6565b909155506117ad90508383613b9f565b6040516001600160a01b0383166024820152604481018290526117ad90849063a9059cbb60e01b906064016123dd565b80600003612a0857505050565b612a11816128a8565b60ca5460405163095ea7b360e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081166004830152602482018490529091169063095ea7b3906044016020604051808303816000875af1158015612a84573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612aa89190615bd1565b5060ca5460405163d683d2c760e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081169263d683d2c792612b0092919091169087908790600401615db5565b600060405180830381600087803b158015612b1a57600080fd5b505af1158015612b2e573d6000803e3d6000fd5b50505050505050565b600054610100900460ff16612ba25760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b60648201526084016113a8565b612bab81613cda565b50565b600054610100900460ff16612c195760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b60648201526084016113a8565b612c416040518060200160405280600081525060405180602001604052806000815250613e00565b612bab81613e75565b600054610100900460ff16612cb55760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b60648201526084016113a8565b565b60008215612ce55781612ccb600185615ad6565b612cd59190615cb0565b612ce0906001615a30565b61098d565b50600092915050565b600082600003612d1157604051632ec86ff560e21b815260040160405180910390fd5b612d2483612d1e609a5490565b84613f88565b6001600160a01b038516600090815260cc602052604081205491925090612d4c908590615a30565b90506fffffffffffffffffffffffffffffffff811115612d7f57604051637756904960e01b815260040160405180910390fd5b6001600160a01b038516600090815260cc6020526040812082905560cd8054869290612dac908490615a30565b909155505060ca543390612dcb906001600160a01b03168230886123a9565b6001600160a01b038616600090815260986020526040812054612def908590615a30565b90506fffffffffffffffffffffffffffffffff811115612e2257604051637756904960e01b815260040160405180910390fd5b612e2c8785613fd4565b866001600160a01b0316826001600160a01b03167fdcde3dce73cebc28787eaab2e2b0474ab6f06f519882e7ee490a3f57e46abed38887604051612e7a929190918252602082015260400190565b60405180910390a35050509392505050565b60006060612e99836128e5565b9092509050612ea88484612924565b60ca54612ebf906001600160a01b031685846129cb565b80516101005460ca54610101546001600160a01b0392831692632eb2c2d69230928a92612eee9216908761409d565b866040518563ffffffff1660e01b8152600401612f0e9493929190615e13565b600060405180830381600087803b158015612f2857600080fd5b505af1158015612f3c573d6000803e3d6000fd5b505050506000612f546097546001600160a01b031690565b9050806001600160a01b0316866001600160a01b031603612fd15760405163d77eb4c760e01b815260048101859052602481018690526001600160a01b0382169063d77eb4c790604401600060405180830381600087803b158015612fb857600080fd5b505af1158015612fcc573d6000803e3d6000fd5b505050505b856001600160a01b03167f96bd1544577eb6c104cdc0a1e4eda89c64f8875c006dfda5baaef1aa5628b4b985858860405161300e93929190615c37565b60405180910390a250509250929050565b600080821161303057613030615ac0565b8161303b8486615c83565b611ee99190615cb0565b6040805161014081018252671bc16d674ec800008152671987adbcfc26e000602082015267177a3b78c9df20009181019190915267156217a05ad140006060820152671318fef1a6c220006080820152671088195fa3c9e00060a0820152670d9941201660e00060c0820152670a32144aa26d000060e082015267062ff6932687600061010082015267016345785d8a00006101208201526000908166b1a2bc2ec500006130fc85826706f05b59d3b20000614151565b6131069190615ad6565b9050600061311b66b1a2bc2ec5000083615cb0565b9050600061313066b1a2bc2ec5000084615e6e565b905060006131496009613144856001615a30565b614175565b905066b1a2bc2ec500008582600a811061316557613165615a43565b60200201518685600a811061317c5761317c615a43565b602002015161318b9190615ad6565b6131959084615c83565b61319f9190615cb0565b8584600a81106131b1576131b1615a43565b60200201516131c09190615ad6565b979650505050505050565b60008285101561325c5760006131e18684615c83565b6131eb8585615c83565b6131f76012600a615bc5565b6132019089615c83565b61320b9190615a30565b6132159190615ad6565b905060006132386132268789615c83565b836132336012600a615bc5565b61418b565b905060006132468680615c83565b90506132528183615cb0565b9350505050611ee9565b50919392505050565b600082518251111561328a5760405163c57d332960e01b815260040160405180910390fd5b60008060005b845181101561331a578581815181106132ab576132ab615a43565b60200260200101518582815181106132c5576132c5615a43565b60200260200101516132d79190615c83565b6132e19084615a30565b92508481815181106132f5576132f5615a43565b6020026020010151826133089190615a30565b915061331381615a59565b9050613290565b506118728282612cb7565b6097546001600160a01b03848116911614801561334a57506001600160a01b03821615155b156117ad576124da8282612e8c565b60008083518351111561337f5760405163c57d332960e01b815260040160405180910390fd5b825187106133a05760405163bdc9571560e01b815260040160405180910390fd5b856000036133c157604051636cdaa7bb60e01b815260040160405180910390fd5b60008060005b85518110156134a157808a1461348f5760006133e56012600a615bc5565b6133ef908d615c83565b90506134218188848151811061340757613407615a43565b6020026020010151898e81518110611e0357611e03615a43565b61342b9085615a30565b935086828151811061343f5761343f615a43565b60200260200101518c8a8a858151811061345b5761345b615a43565b602002602001015161346d9190615a30565b6134779190615a30565b6134819190615c83565b61348b9084615a30565b9250505b8061349981615a59565b9150506133c7565b5060006134b9868b81518110611e4757611e47615a43565b905061350088888c815181106134d1576134d1615a43565b60200260200101516134e39190615a30565b6134ef6012600a615bc5565b6134f99086615cb0565b8b8461423a565b925061350e6012600a615bc5565b6135189084615cb0565b9450858a8151811061352c5761352c615a43565b60200260200101518589898d8151811061354857613548615a43565b602002602001015161355a9190615a30565b6135649190615ad6565b61356e9190615c83565b6135789083615a30565b91506135906135896012600a615bc5565b8390612cb7565b9350505050965096945050505050565b6000806135c760405180606001604052806000815260200160008152602001600081525090565b5060408051606081018252600080825260208201819052918101829052845190916135f1876122a3565b90508186602001516136039190615a30565b9450600061363b8860400151838151811061362057613620615a43565b6020026020010151886060015161453790919063ffffffff16565b9050600061366f89604001518c8151811061365857613658615a43565b60200260200101518861453790919063ffffffff16565b905061367b828261454d565b955050508184106136905781840383526136dc565b838203886136a0576136a0615ac0565b6000886020015188604001516136b69190615ad6565b602086018390529050806136ca8b84615c83565b6136d49190615cb0565b604086015250505b838288602001516136ed9190615a30565b6136f79190615ad6565b602088015260005b87604001515181101561374c57848860400151828151811061372357613723615a43565b602002602001018181516137379190615a30565b9052508061374481615a59565b9150506136ff565b508487604001518a8151811061376457613764615a43565b602002602001018181516137789190615ad6565b9052506060860151604088015180518390811061379757613797615a43565b602002602001018181516137ab9190615ad6565b9150818152505050509450945094915050565b6000600182516107ea9190615ad6565b6000613823826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661455c9092919063ffffffff16565b8051909150156117ad57808060200190518101906138419190615bd1565b6117ad5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016113a8565b6138a8610c72565b8111156138c8576040516311d681c960e21b815260040160405180910390fd5b806000036138d35750565b8060cb60008282546138e59190615a30565b90915550506040518181527f7545428d48c07276e600a1b3c9689be2420624a568454764744bed2ed4785b5e9060200160405180910390a150565b80158061399a5750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa158015613974573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139989190615aa7565b155b613a0c5760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527f20746f206e6f6e2d7a65726f20616c6c6f77616e63650000000000000000000060648201526084016113a8565b6040516001600160a01b0383166024820152604481018290526117ad90849063095ea7b360e01b906064016123dd565b600082841115613a5f576040516302075cc160e41b815260040160405180910390fd5b831561098d578261303b8584615c83565b606082841115613a93576040516302075cc160e41b815260040160405180910390fd5b815167ffffffffffffffff811115613aad57613aad6155bb565b604051908082528060200260200182016040528015613ad6578160200160208202803683370190505b509050831561098d5760005b8251811015613b4a578385848381518110613aff57613aff615a43565b6020026020010151613b119190615c83565b613b1b9190615cb0565b828281518110613b2d57613b2d615a43565b602090810291909101015280613b4281615a59565b915050613ae2565b509392505050565b600083831115613b75576040516302075cc160e41b815260040160405180910390fd5b8315613b955783613b868484615c83565b613b909190615cb0565b611ee9565b6000949350505050565b6001600160a01b038216613bff5760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b60648201526084016113a8565b6001600160a01b03821660009081526098602052604090205481811015613c735760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b60648201526084016113a8565b6001600160a01b03831660008181526098602090815260408083208686039055609a80548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a36117ad83600084613325565b600054610100900460ff16613d455760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b60648201526084016113a8565b6097546001600160a01b031615613d5e57613d5e615ac0565b6001600160a01b03811615801590613d8d5750613d8b6001600160a01b038216636831974d60e11b61456b565b155b15613db6576040516320d6c2ad60e01b81526001600160a01b03821660048201526024016113a8565b609780546001600160a01b0319166001600160a01b0383169081179091556040517f18da49b0178612731ce8a0d4a3052637cc23b8bfb85385e67c4373011d86ed1390600090a250565b600054610100900460ff16613e6b5760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b60648201526084016113a8565b6123a58282614587565b600054610100900460ff16613ee05760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b60648201526084016113a8565b6012816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613f20573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f449190615c60565b60ff161115613f66576040516347aad2ef60e11b815260040160405180910390fd5b60ca80546001600160a01b0319166001600160a01b0392909216919091179055565b600081613f9481615a59565b9250613fa490506004600a615bc5565b613fae9084615a30565b925060008311613fc057613fc0615ac0565b611ee982613fce8587615c83565b90612cb7565b6001600160a01b03821661402a5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f20616464726573730060448201526064016113a8565b80609a600082825461403c9190615a30565b90915550506001600160a01b0382166000818152609860209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a36123a560008383613325565b60608167ffffffffffffffff8111156140b8576140b86155bb565b6040519080825280602002602001820160405280156140e1578160200160208202803683370190505b50905060005b82811015613b4a5760408051602080820187905281830184905282518083038401815260609092019092528051910120614122908690610be6565b82828151811061413457614134615a43565b60209081029190910101528061414981615a59565b9150506140e7565b600082841061416d578184116141675783611ee9565b81611ee9565b509092915050565b6000818310614184578161098d565b5090919050565b60008080600019858709858702925082811083820303915050806000036141c5578382816141bb576141bb615c9a565b049250505061098d565b8084116141d157600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b60008060006142578661424d878a614175565b613144908a615ad6565b90506142656012600a615bc5565b61426f9082615c83565b925061427b8188615ad6565b96506142878187615ad6565b915050801561452e578560000361429e5750611ee9565b838611156142ae576142ae615ac0565b67016345785d8a00008310156142c6576142c6615ac0565b671bc16d674ec800008311156142de576142de615ac0565b60006142e98761460b565b905060006142f78886615c83565b905060006143058288614652565b905060006143138588615c83565b90506000614321828a614661565b905061433681680727de34a24f900000111590565b15614373576143476012600a615bc5565b61435260018d615ad6565b61435c9190615c83565b6143669088615a30565b9650505050505050611ee9565b60006143998561439361438c6143898e8e615c83565b90565b8990614670565b90614682565b905060006143a983620f42401190565b1561442457816143b98186614694565b92506143cf6143c8848e614661565b8290614670565b90506143fd6143c88d6143e3816002615c83565b6143ed9190615c83565b6143f78689614694565b90614661565b9050600061440f896143938a85614670565b905061441b87826146a3565b925050506144d6565b614436614431605061460b565b841090565b1561447c576000614446846146ca565b905060006144548285614694565b905060006144668a6143938b85614670565b905061447288826146a3565b93505050506144d6565b600061448f61448a856146ca565b614718565b905060008e6144a583866132336012600a615bc5565b6144ae8a614718565b6144b89190615a30565b6144c29190615ad6565b90506144d16143898289613fce565b925050505b6144e781670de0b6b3a76400001190565b6144f157806144fb565b670de0b6b3a76400005b90508087101561450d5761450d615ac0565b61451a6143898883614682565b614524908a615a30565b9850505050505050505b50949350505050565b600081831161454757600061098d565b50900390565b6000818311614184578161098d565b6060611ee9848460008561472c565b6000614576836147fc565b801561098d575061098d838361482f565b600054610100900460ff166145f25760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b60648201526084016113a8565b609b6145fe8382615ed0565b50609c6117ad8282615ed0565b6000614621670de0b6b3a7640000600019615cb0565b82111561464457604051631cd951a760e01b8152600481018390526024016113a8565b50670de0b6b3a76400000290565b600061098d6143898385615c83565b600061098d6143898385615cb0565b600061098d82845b6143899190615a30565b600061098d82845b6143899190615ad6565b600061098d61438984846148b4565b60008215612ce557612ce06146c3836146bd86600161496a565b90614976565b600161498e565b600081680736ea4425c11ac6308111156146fa57604051630d7b1d6560e11b8152600481018490526024016113a8565b6714057b7ef767814f8102611ee9670de0b6b3a7640000820461499a565b60006107ea670de0b6b3a764000083615cb0565b60608247101561478d5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016113a8565b600080866001600160a01b031685876040516147a99190615f90565b60006040518083038185875af1925050503d80600081146147e6576040519150601f19603f3d011682016040523d82523d6000602084013e6147eb565b606091505b50915091506131c0878383876149f0565b600061480f826301ffc9a760e01b61482f565b80156107ea5750614828826001600160e01b031961482f565b1592915050565b604080516001600160e01b03198316602480830191909152825180830390910181526044909101909152602080820180516001600160e01b03166301ffc9a760e01b178152825160009392849283928392918391908a617530fa92503d915060005190508280156148a1575060208210155b80156131c0575015159695505050505050565b60008080600019848609848602925082811083820303915050806000036148e85750670de0b6b3a7640000900490506107ea565b670de0b6b3a7640000811061491a57604051635173648d60e01b815260048101869052602481018590526044016113a8565b6000670de0b6b3a764000085870962040000818503049310909103600160ee1b02919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690291505092915050565b600061098d828461468a565b600061098d61438984670de0b6b3a764000085614a69565b600061098d8284614678565b600081680a688906bd8affffff8111156149ca5760405163b3b6ba1f60e01b8152600481018490526024016113a8565b60006149e2670de0b6b3a7640000604084901b615cb0565b9050611ee961438982614aca565b60608315614a5f578251600003614a58576001600160a01b0385163b614a585760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016113a8565b5081611ee9565b611ee9838361522a565b6000808060001985870985870292508281108382030391505080600003614a99578382816141bb576141bb615c9a565b8381106141d157604051630c740aef60e31b81526004810187905260248101869052604481018590526064016113a8565b600160bf1b67ff00000000000000821615614bd757678000000000000000821615614afe5768016a09e667f3bcc9090260401c5b674000000000000000821615614b1d576801306fe0a31b7152df0260401c5b672000000000000000821615614b3c576801172b83c7d517adce0260401c5b671000000000000000821615614b5b5768010b5586cf9890f62a0260401c5b670800000000000000821615614b7a576801059b0d31585743ae0260401c5b670400000000000000821615614b9957680102c9a3e778060ee70260401c5b670200000000000000821615614bb85768010163da9fb33356d80260401c5b670100000000000000821615614bd757680100b1afa5abcbed610260401c5b66ff000000000000821615614cd6576680000000000000821615614c045768010058c86da1c09ea20260401c5b6640000000000000821615614c22576801002c605e2e8cec500260401c5b6620000000000000821615614c4057680100162f3904051fa10260401c5b6610000000000000821615614c5e576801000b175effdc76ba0260401c5b6608000000000000821615614c7c57680100058ba01fb9f96d0260401c5b6604000000000000821615614c9a5768010002c5cc37da94920260401c5b6602000000000000821615614cb8576801000162e525ee05470260401c5b6601000000000000821615614cd65768010000b17255775c040260401c5b65ff0000000000821615614dcc5765800000000000821615614d01576801000058b91b5bc9ae0260401c5b65400000000000821615614d1e57680100002c5c89d5ec6d0260401c5b65200000000000821615614d3b5768010000162e43f4f8310260401c5b65100000000000821615614d5857680100000b1721bcfc9a0260401c5b65080000000000821615614d755768010000058b90cf1e6e0260401c5b65040000000000821615614d92576801000002c5c863b73f0260401c5b65020000000000821615614daf57680100000162e430e5a20260401c5b65010000000000821615614dcc576801000000b1721835510260401c5b64ff00000000821615614eb957648000000000821615614df557680100000058b90c0b490260401c5b644000000000821615614e115768010000002c5c8601cc0260401c5b642000000000821615614e2d576801000000162e42fff00260401c5b641000000000821615614e495768010000000b17217fbb0260401c5b640800000000821615614e65576801000000058b90bfce0260401c5b640400000000821615614e8157680100000002c5c85fe30260401c5b640200000000821615614e9d5768010000000162e42ff10260401c5b640100000000821615614eb957680100000000b17217f80260401c5b63ff000000821615614f9d576380000000821615614ee05768010000000058b90bfc0260401c5b6340000000821615614efb576801000000002c5c85fe0260401c5b6320000000821615614f1657680100000000162e42ff0260401c5b6310000000821615614f31576801000000000b17217f0260401c5b6308000000821615614f4c57680100000000058b90c00260401c5b6304000000821615614f675768010000000002c5c8600260401c5b6302000000821615614f82576801000000000162e4300260401c5b6301000000821615614f9d5768010000000000b172180260401c5b62ff00008216156150785762800000821615614fc2576801000000000058b90c0260401c5b62400000821615614fdc57680100000000002c5c860260401c5b62200000821615614ff65768010000000000162e430260401c5b6210000082161561501057680100000000000b17210260401c5b6208000082161561502a5768010000000000058b910260401c5b62040000821615615044576801000000000002c5c80260401c5b6202000082161561505e57680100000000000162e40260401c5b62010000821615615078576801000000000000b1720260401c5b61ff0082161561514a5761800082161561509b57680100000000000058b90260401c5b6140008216156150b45768010000000000002c5d0260401c5b6120008216156150cd576801000000000000162e0260401c5b6110008216156150e65768010000000000000b170260401c5b6108008216156150ff576801000000000000058c0260401c5b61040082161561511857680100000000000002c60260401c5b61020082161561513157680100000000000001630260401c5b61010082161561514a57680100000000000000b10260401c5b60ff82161561521357608082161561516b57680100000000000000590260401c5b6040821615615183576801000000000000002c0260401c5b602082161561519b57680100000000000000160260401c5b60108216156151b3576801000000000000000b0260401c5b60088216156151cb57680100000000000000060260401c5b60048216156151e357680100000000000000030260401c5b60028216156151fb57680100000000000000010260401c5b600182161561521357680100000000000000010260401c5b670de0b6b3a76400000260409190911c60bf031c90565b81511561523a5781518083602001fd5b8060405162461bcd60e51b81526004016113a891906152a2565b60006020828403121561526657600080fd5b81356001600160e01b03198116811461098d57600080fd5b60005b83811015615299578181015183820152602001615281565b50506000910152565b60208152600082518060208401526152c181604085016020870161527e565b601f01601f19169190910160400192915050565b6001600160a01b0381168114612bab57600080fd5b600080604083850312156152fd57600080fd5b8235615308816152d5565b946020939093013593505050565b600081518084526020808501945080840160005b838110156153465781518752958201959082019060010161532a565b509495945050505050565b60208152600061098d6020830184615316565b60006020828403121561537657600080fd5b813561098d816152d5565b60008060006060848603121561539657600080fd5b83356153a1816152d5565b925060208401356153b1816152d5565b929592945050506040919091013590565b60008083601f8401126153d457600080fd5b50813567ffffffffffffffff8111156153ec57600080fd5b6020830191508360208260051b850101111561540757600080fd5b9250929050565b6000806020838503121561542157600080fd5b823567ffffffffffffffff81111561543857600080fd5b615444858286016153c2565b90969095509350505050565b60008060006060848603121561546557600080fd5b505081359360208301359350604090920135919050565b8381528260208201526060604082015260006118726060830184615316565b600080604083850312156154ae57600080fd5b50508035926020909101359150565b6000602082840312156154cf57600080fd5b5035919050565b60008060008060008060c087890312156154ef57600080fd5b86356154fa816152d5565b9860208801359850604088013597606081013597506080810135965060a00135945092505050565b6040815260006155356040830185615316565b90508260208301529392505050565b60008082840360e081121561555857600080fd5b60a081121561556657600080fd5b8392506040609f198201121561557b57600080fd5b5060a0830190509250929050565b60006020828403121561559b57600080fd5b81356fffffffffffffffffffffffffffffffff8116811461098d57600080fd5b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156155fa576155fa6155bb565b604052919050565b600067ffffffffffffffff82111561561c5761561c6155bb565b5060051b60200190565b600082601f83011261563757600080fd5b8135602061564c61564783615602565b6155d1565b82815260059290921b8401810191818101908684111561566b57600080fd5b8286015b84811015615686578035835291830191830161566f565b509695505050505050565b600082601f8301126156a257600080fd5b813567ffffffffffffffff8111156156bc576156bc6155bb565b6156cf601f8201601f19166020016155d1565b8181528460208386010111156156e457600080fd5b816020850160208301376000918101602001919091529392505050565b600080600080600060a0868803121561571957600080fd5b8535615724816152d5565b94506020860135615734816152d5565b9350604086013567ffffffffffffffff8082111561575157600080fd5b61575d89838a01615626565b9450606088013591508082111561577357600080fd5b61577f89838a01615626565b9350608088013591508082111561579557600080fd5b506157a288828901615691565b9150509295509295909350565b600080600080608085870312156157c557600080fd5b84356157d0816152d5565b966020860135965060408601359560600135945092505050565b600080604083850312156157fd57600080fd5b8235615808816152d5565b91506020830135615818816152d5565b809150509250929050565b828152604060208201526000611ee96040830184615316565b60408152600060a0820184516040840152602080860151606085015260408601516060608086015282815180855260c0870191508383019450600092505b8083101561589a578451825293830193600192909201919083019061587a565b50858103838701526158ac8188615316565b98975050505050505050565b600080600080600060a086880312156158d057600080fd5b85356158db816152d5565b945060208601356158eb816152d5565b93506040860135925060608601359150608086013567ffffffffffffffff81111561591557600080fd5b6157a288828901615691565b600181811c9082168061593557607f821691505b60208210810361595557634e487b7160e01b600052602260045260246000fd5b50919050565b600082601f83011261596c57600080fd5b8151602061597c61564783615602565b82815260059290921b8401810191818101908684111561599b57600080fd5b8286015b84811015615686578051835291830191830161599f565b600080604083850312156159c957600080fd5b825167ffffffffffffffff808211156159e157600080fd5b6159ed8683870161595b565b93506020850151915080821115615a0357600080fd5b50615a108582860161595b565b9150509250929050565b634e487b7160e01b600052601160045260246000fd5b808201808211156107ea576107ea615a1a565b634e487b7160e01b600052603260045260246000fd5b600060018201615a6b57615a6b615a1a565b5060010190565b600060208284031215615a8457600080fd5b815167ffffffffffffffff811115615a9b57600080fd5b611ee98482850161595b565b600060208284031215615ab957600080fd5b5051919050565b634e487b7160e01b600052600160045260246000fd5b818103818111156107ea576107ea615a1a565b600181815b80851115610b08578160001904821115615b0a57615b0a615a1a565b80851615615b1757918102915b93841c9390800290615aee565b600082615b33575060016107ea565b81615b40575060006107ea565b8160018114615b565760028114615b6057615b7c565b60019150506107ea565b60ff841115615b7157615b71615a1a565b50506001821b6107ea565b5060208310610133831016604e8410600b8410161715615b9f575081810a6107ea565b615ba98383615ae9565b8060001904821115615bbd57615bbd615a1a565b029392505050565b600061098d8383615b24565b600060208284031215615be357600080fd5b8151801515811461098d57600080fd5b60006001600160a01b03808816835280871660208401525084604083015260a06060830152615c2560a0830185615316565b82810360808401526158ac8185615316565b838152606060208201526000615c506060830185615316565b9050826040830152949350505050565b600060208284031215615c7257600080fd5b815160ff8116811461098d57600080fd5b80820281158282048414176107ea576107ea615a1a565b634e487b7160e01b600052601260045260246000fd5b600082615cbf57615cbf615c9a565b500490565b60008060408385031215615cd757600080fd5b505080516020909101519092909150565b60008060408385031215615cfb57600080fd5b825167ffffffffffffffff811115615d1257600080fd5b615d1e8582860161595b565b925050602083015190509250929050565b60006020808385031215615d4257600080fd5b825167ffffffffffffffff811115615d5957600080fd5b8301601f81018513615d6a57600080fd5b8051615d7861564782615602565b81815260059190911b82018301908381019087831115615d9757600080fd5b928401925b828410156131c057835182529284019290840190615d9c565b6000606082016001600160a01b03861683526020606081850152818651808452608086019150828801935060005b81811015615dff57845183529383019391830191600101615de3565b505084810360408601526158ac8187615316565b60006001600160a01b03808716835280861660208401525060a06040830152615e3f60a0830185615316565b8281036060840152615e518185615316565b838103608090940193909352505060008152602001949350505050565b600082615e7d57615e7d615c9a565b500690565b601f8211156117ad57600081815260208120601f850160051c81016020861015615ea95750805b601f850160051c820191505b81811015615ec857828155600101615eb5565b505050505050565b815167ffffffffffffffff811115615eea57615eea6155bb565b615efe81615ef88454615921565b84615e82565b602080601f831160018114615f335760008415615f1b5750858301515b600019600386901b1c1916600185901b178555615ec8565b600085815260208120601f198616915b82811015615f6257888601518255948401946001909101908401615f43565b5085821015615f805787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b60008251615fa281846020870161527e565b919091019291505056fea2646970667358221220b3d97b482525cf969c4a7d5c761393e2eb1aa16189ac94d798fa1ce48197bb7564736f6c63430008130033496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206900000000000000000000000056321a3f1b7a1de1a092829e1b0c72db4ab1b225000000000000000000000000d14d2f62949e83708af8633ed555752923c9b9fe0000000000000000000000004720cda43b2bfb177d42a99538d01362543f0a67
Deployed Bytecode
0x608060405234801561001057600080fd5b50600436106101515760003560e01c80635c975abb116100cd578063a217fddf11610081578063b4b1516711610066578063b4b1516714610303578063d547741f14610316578063e0578fce1461032957600080fd5b8063a217fddf146102e8578063aecc550a146102f057600080fd5b80638456cb59116100b25780638456cb59146102945780639026dee81461029c57806391d14854146102af57600080fd5b80635c975abb1461027657806383edf3171461028157600080fd5b80632a2d1c1b1161012457806336568abe1161010957806336568abe146102485780633f4ba83a1461025b5780634a1097c71461026357600080fd5b80632a2d1c1b146102085780632f2ff15d1461023357600080fd5b806301ffc9a71461015657806307bd02651461017e57806318ea084f146101b3578063248a9ca3146101e5575b600080fd5b6101696101643660046111a8565b61033c565b60405190151581526020015b60405180910390f35b6101a57fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e6381565b604051908152602001610175565b6101c66101c13660046111ea565b61039d565b604080516001600160a01b039093168352602083019190915201610175565b6101a56101f3366004611252565b60009081526065602052604090206001015490565b61021b610216366004611317565b6103be565b6040516001600160a01b039091168152602001610175565b610246610241366004611422565b6103d3565b005b610246610256366004611422565b6103fd565b61024661048e565b6101c66102713660046111ea565b6104a1565b60975460ff16610169565b61024661028f366004611452565b610553565b610246610580565b6102466102aa366004611452565b610591565b6101696102bd366004611422565b60009182526065602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6101a5600081565b61021b6102fe36600461148f565b61059c565b61021b610311366004611317565b61061d565b610246610324366004611422565b61078a565b61021b6103373660046115a1565b6107af565b60006001600160e01b031982166357662a8560e11b148061036d57506001600160e01b0319821663b4b1516760e01b145b8061038857506001600160e01b03198216634a1097c760e01b145b806103975750610397826107e8565b92915050565b6000806000806103af888888886104a1565b90999098509650505050505050565b60006103cb84848461061d565b949350505050565b6000828152606560205260409020600101546103ee8161081d565b6103f88383610827565b505050565b6001600160a01b03811633146104805760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201527f20726f6c657320666f722073656c66000000000000000000000000000000000060648201526084015b60405180910390fd5b61048a82826108c9565b5050565b61049733610591565b61049f61094c565b565b600080806104b26020870187611452565b6001600160a01b031663289ab7e26104d060a0890160808a01611452565b87876040518463ffffffff1660e01b81526004016104f093929190611667565b60408051808303816000875af115801561050e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105329190611721565b909250905061054787878363ffffffff61099e565b92505094509492505050565b61057d7fd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e6382610b52565b50565b61058933610591565b61049f610bc7565b61057d600082610b52565b600063ffffffff8016826060015111156105c957604051635ec5096760e11b815260040160405180910390fd5b60006040518060600160405280846000015181526020016105f48560200151655af3107a4000610c04565b8152602001846060015163ffffffff16815250905061061485858361061d565b95945050505050565b600061062833610553565b60006106378360200151610cb9565b61064290600161175b565b9050600181116106655760405163104272fb60e11b815260040160405180910390fd5b61068f633eafa4fd60e11b61068060a0870160808801611452565b6001600160a01b031690610cc9565b6106c8576106a360a0850160808601611452565b60405163c5a5657d60e01b81526001600160a01b039091166004820152602401610477565b60006106da60a0860160808701611452565b905060006001600160a01b038216630e8a8cf36106fa6020890189611452565b87600001518689602001518a604001516040518663ffffffff1660e01b815260040161072a9594939291906117be565b6020604051808303816000875af1158015610749573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061076d9190611804565b905061077f878783886040015161099e565b979650505050505050565b6000828152606560205260409020600101546107a58161081d565b6103f883836108c9565b6000806107bc8484610cec565b90506103cb7f0000000000000000000000000e0ab5e993283de24be854df82397bae15a0b02f82610d7e565b60006001600160e01b03198216637965db0b60e01b148061039757506301ffc9a760e01b6001600160e01b0319831614610397565b61057d8133610b52565b60008281526065602090815260408083206001600160a01b038516845290915290205460ff1661048a5760008281526065602090815260408083206001600160a01b03851684529091529020805460ff191660011790556108853390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60008281526065602090815260408083206001600160a01b038516845290915290205460ff161561048a5760008281526065602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b610954610dde565b6097805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b6000806109ab8585610cec565b604080518082019091528581526020810188905290915060006109ee7f0000000000000000000000000e0ab5e993283de24be854df82397bae15a0b02f84610d7e565b90506001600160a01b0381163b15610a0a5792506103cb915050565b6000610a367f0000000000000000000000000e0ab5e993283de24be854df82397bae15a0b02f85610e30565b9050816001600160a01b0316816001600160a01b031614610a5957610a5961181d565b81610a6a60408a0160208b01611452565b6001600160a01b0316610a8060208b018b611452565b8551602080880151604080516001600160a01b0388811682529381019490945263ffffffff8d16908401526060830152919091169033907f2d357fefe8d7e1012a0782310cc7c7c6670f306a0d1e035815e27c11a5ea8c879060800160405180910390a460405163ae3afc0360e01b81526001600160a01b0382169063ae3afc0390610b12908c908890600401611833565b600060405180830381600087803b158015610b2c57600080fd5b505af1158015610b40573d6000803e3d6000fd5b50929c9b505050505050505050505050565b60008281526065602090815260408083206001600160a01b038516845290915290205460ff1661048a57610b8581610ecd565b610b90836020610edf565b604051602001610ba19291906118c1565b60408051601f198184030181529082905262461bcd60e51b825261047791600401611942565b610bcf611088565b6097805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586109813390565b81516060906002810267ffffffffffffffff811115610c2557610c2561126b565b6040519080825280601f01601f191660200182016040528015610c4f576020820181803683370190505b50915060005b81811015610cb157600084868381518110610c7257610c72611955565b602002602001015181610c8757610c8761196b565b04905061ffff811115610c9c57610c9c61181d565b60f01b60028202840160200152600101610c55565b505092915050565b6000600282516103979190611981565b6000610cd4836110db565b8015610ce55750610ce5838361110e565b9392505050565b6000610cfb6020840184611452565b610d0b6040850160208601611452565b610d1b6060860160408701611452565b610d2b60a0870160808801611452565b604080516001600160a01b039586166020820152938516908401529083166060830152909116608082015260a0810183905260c00160405160208183030381529060405280519060200120905092915050565b6040513060388201526f5af43d82803e903d91602b57fd5bf3ff602482015260148101839052733d602d80600a3d3981f3363d3d373d3d3d363d738152605881018290526037600c82012060788201526055604390910120600090610ce5565b60975460ff1661049f5760405162461bcd60e51b815260206004820152601460248201527f5061757361626c653a206e6f74207061757365640000000000000000000000006044820152606401610477565b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b1760205281603760096000f590506001600160a01b0381166103975760405162461bcd60e51b815260206004820152601760248201527f455243313136373a2063726561746532206661696c65640000000000000000006044820152606401610477565b60606103976001600160a01b03831660145b60606000610eee8360026119a3565b610ef990600261175b565b67ffffffffffffffff811115610f1157610f1161126b565b6040519080825280601f01601f191660200182016040528015610f3b576020820181803683370190505b509050600360fc1b81600081518110610f5657610f56611955565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110610f8557610f85611955565b60200101906001600160f81b031916908160001a9053506000610fa98460026119a3565b610fb490600161175b565b90505b6001811115611039577f303132333435363738396162636465660000000000000000000000000000000085600f1660108110610ff557610ff5611955565b1a60f81b82828151811061100b5761100b611955565b60200101906001600160f81b031916908160001a90535060049490941c93611032816119ba565b9050610fb7565b508315610ce55760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610477565b60975460ff161561049f5760405162461bcd60e51b815260206004820152601060248201527f5061757361626c653a20706175736564000000000000000000000000000000006044820152606401610477565b60006110ee826301ffc9a760e01b61110e565b80156103975750611107826001600160e01b031961110e565b1592915050565b604080516001600160e01b03198316602480830191909152825180830390910181526044909101909152602080820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166301ffc9a760e01b178152825160009392849283928392918391908a617530fa92503d91506000519050828015611195575060208210155b801561077f575015159695505050505050565b6000602082840312156111ba57600080fd5b81356001600160e01b031981168114610ce557600080fd5b600060a082840312156111e457600080fd5b50919050565b600080600080610100858703121561120157600080fd5b8435935061121286602087016111d2565b925060c0850135915060e085013567ffffffffffffffff81111561123557600080fd5b85016060818803121561124757600080fd5b939692955090935050565b60006020828403121561126457600080fd5b5035919050565b634e487b7160e01b600052604160045260246000fd5b6040516060810167ffffffffffffffff811182821017156112a4576112a461126b565b60405290565b6040516080810167ffffffffffffffff811182821017156112a4576112a461126b565b604051601f8201601f1916810167ffffffffffffffff811182821017156112f6576112f661126b565b604052919050565b803563ffffffff8116811461131257600080fd5b919050565b600080600060e0848603121561132c57600080fd5b83359250602061133e868287016111d2565b925060c085013567ffffffffffffffff8082111561135b57600080fd5b908601906060828903121561136f57600080fd5b611377611281565b82358152838301358281111561138c57600080fd5b8301601f81018a1361139d57600080fd5b8035838111156113af576113af61126b565b6113c1601f8201601f191687016112cd565b93508084528a868284010111156113d757600080fd5b80868301878601376000868286010152505081848201526113fa604084016112fe565b6040820152809450505050509250925092565b6001600160a01b038116811461057d57600080fd5b6000806040838503121561143557600080fd5b8235915060208301356114478161140d565b809150509250929050565b60006020828403121561146457600080fd5b8135610ce58161140d565b80356fffffffffffffffffffffffffffffffff8116811461131257600080fd5b600080600060e084860312156114a457600080fd5b8335925060206114b6868287016111d2565b925060c085013567ffffffffffffffff808211156114d357600080fd5b90860190608082890312156114e757600080fd5b6114ef6112aa565b82358152838301358281111561150457600080fd5b8301601f81018a1361151557600080fd5b8035838111156115275761152761126b565b8060051b93506115388685016112cd565b818152938201860193868101908c86111561155257600080fd5b928701925b8584101561157057833582529287019290870190611557565b84880152506115849150506040840161146f565b604082015260608301356060820152809450505050509250925092565b60008060c083850312156115b457600080fd5b6115be84846111d2565b9460a0939093013593505050565b6000808335601e198436030181126115e357600080fd5b830160208101925035905067ffffffffffffffff81111561160357600080fd5b8060051b360382131561161557600080fd5b9250929050565b81835260007f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83111561164e57600080fd5b8260051b80836020870137939093016020019392505050565b6001600160a01b03841681526000602084818401526060604084015260c0830161169185866115cc565b606086810152918290529060009060e086015b818310156116c25783358152928401926001929092019184016116a4565b6116ce858901896115cc565b95509350605f199250828782030160808801526116ec81868661161c565b945050506116fd60408701876115cc565b9250818685030160a087015261171484848361161c565b9998505050505050505050565b6000806040838503121561173457600080fd5b505080516020909101519092909150565b634e487b7160e01b600052601160045260246000fd5b8082018082111561039757610397611745565b60005b83811015611789578181015183820152602001611771565b50506000910152565b600081518084526117aa81602086016020860161176e565b601f01601f19169290920160200192915050565b6001600160a01b038616815284602082015283604082015260a0606082015260006117ec60a0830185611792565b905063ffffffff831660808301529695505050505050565b60006020828403121561181657600080fd5b5051919050565b634e487b7160e01b600052600160045260246000fd5b60e0810183356118428161140d565b6001600160a01b03908116835260208501359061185e8261140d565b90811660208401526040850135906118758261140d565b908116604084015260608501359061188c8261140d565b90811660608401526080850135906118a38261140d565b166080830152825160a083015260209092015160c090910152919050565b7f416363657373436f6e74726f6c3a206163636f756e74200000000000000000008152600083516118f981601785016020880161176e565b7f206973206d697373696e6720726f6c6520000000000000000000000000000000601791840191820152835161193681602884016020880161176e565b01602801949350505050565b602081526000610ce56020830184611792565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601260045260246000fd5b60008261199e57634e487b7160e01b600052601260045260246000fd5b500490565b808202811582820484141761039757610397611745565b6000816119c9576119c9611745565b50600019019056fea2646970667358221220f9f5d2a0daf41405fba8c292024aae140959da94319ead270aa72484a372ad4264736f6c63430008130033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000056321a3f1b7a1de1a092829e1b0c72db4ab1b225000000000000000000000000d14d2f62949e83708af8633ed555752923c9b9fe0000000000000000000000004720cda43b2bfb177d42a99538d01362543f0a67
-----Decoded View---------------
Arg [0] : feeDistributor (address): 0x56321A3F1b7a1de1A092829e1B0c72db4Ab1b225
Arg [1] : admin (address): 0xd14D2F62949e83708af8633eD555752923c9b9fe
Arg [2] : executor (address): 0x4720cdA43b2BfB177D42a99538d01362543f0A67
-----Encoded View---------------
3 Constructor Arguments found :
Arg [0] : 00000000000000000000000056321a3f1b7a1de1a092829e1b0c72db4ab1b225
Arg [1] : 000000000000000000000000d14d2f62949e83708af8633ed555752923c9b9fe
Arg [2] : 0000000000000000000000004720cda43b2bfb177d42a99538d01362543f0a67
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.