Source Code
Overview
POL Balance
More Info
ContractCreator
Multichain Info
N/A
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Latest 25 internal transactions (View All)
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.17+commit.8df45f5f
Optimization Enabled:
Yes with 200 runs
Other Settings:
london EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { ERC165 } from "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol"; import { IMarketFactory } from "./IMarketFactory.sol"; import { IMarketMakerV1, MarketMaker, MarketAddressParams } from "./MarketMaker.sol"; import { MarketErrors } from "./MarketErrors.sol"; import { IConditionalTokens, ConditionID, QuestionID } from "../conditions/IConditionalTokens.sol"; import { ArrayMath } from "../Math.sol"; contract MarketMakerFactory is MarketErrors, IMarketFactory, ERC165 { using ArrayMath for uint256[]; using SafeERC20 for IERC20Metadata; using Address for address; address private immutable marketTemplate; /// @notice Invalid funds parameter for create and fund error InvalidFundsLength(); constructor() { marketTemplate = address(new MarketMaker()); } /// @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, PriceMarketParams memory params) public returns (IMarketMakerV1) { uint256 outcomeSlotCount = params.fairPriceDecimals.length; if (outcomeSlotCount == 0) revert InvalidPrices(); // prepareCondition is idempotent, so should not fail if already exists ConditionID conditionId = addresses.conditionalTokens.prepareCondition(addresses.conditionOracle, params.questionId, outcomeSlotCount); // 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, params.haltTime, fee, params.fairPriceDecimals, params.minPriceDecimal); // 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, initParams.haltTime, initParams.fee ); market.initialize(addresses, initParams); return market; } /// @notice Creates markets and funds them in a single call /// @param marketParamsArray unique parameters for every market /// @return the created and funded market function createAndFundMarketsWithPrices( uint256 fee, MarketAddressParams calldata addresses, PriceMarketParams[] memory marketParamsArray, uint256[] memory addedFunds ) public returns (MarketMaker[] memory) { if (addedFunds.length != marketParamsArray.length) revert InvalidFundsLength(); MarketMaker[] memory markets = new MarketMaker[](marketParamsArray.length); addresses.collateralToken.safeTransferFrom(msg.sender, address(this), addedFunds.sum()); uint256 totalToSendBack = 0; for (uint256 i = 0; i < marketParamsArray.length; ++i) { MarketMaker market = createMarketConcrete(fee, addresses, marketParamsArray[i]); markets[i] = market; if (market.reserves() > 0) { // if already funded, send funds back totalToSendBack += addedFunds[i]; } else if (addedFunds[i] > 0) { // otherwise fund it addresses.collateralToken.safeApprove(address(market), addedFunds[i]); // Ignore return because we don't care about liquidity shares // returned. It should equal addedFunds since this will be the first // funding // slither-disable-next-line unused-return market.addFundingFor(msg.sender, addedFunds[i]); } } if (totalToSendBack > 0) { addresses.collateralToken.safeTransfer(msg.sender, totalToSendBack); } return markets; } /// @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, PriceMarketParams memory params) public returns (MarketMaker) { return MarketMaker(address(createMarket(fee, addresses, params))); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IMarketFactory).interfaceId || ERC165.supportsInterface(interfaceId); } /// @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) { return keccak256(abi.encode(addresses, conditionId)); } }
// 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 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 (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 v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.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 ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
// 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 pragma solidity ^0.8.17; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import { IMarketMakerV1 } from "./IMarketMaker.sol"; import { MarketAddressParams } from "./MarketAddressParams.sol"; import { IConditionalTokens, ConditionID, QuestionID } from "../conditions/IConditionalTokens.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); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; 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 { IConditionalTokens, ConditionID, ConditionalTokensErrors } from "../conditions/IConditionalTokens.sol"; import { IUpdateHaltTime } from "../conditions/IUpdateHaltTime.sol"; import { FundingPool, IFundingPoolV1_1, IFundingPoolV1 } from "../funding/FundingPool.sol"; import { ChildFundingPool, IChildFundingPoolV1, IParentFundingPoolV1 } from "../funding/ChildFundingPool.sol"; import { IMarketMakerV1 } from "./IMarketMaker.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, ChildFundingPool, FundingPool, IUpdateHaltTime, ConditionalTokensErrors { using ArrayMath for uint256[]; using Math for uint256; using ClampedMath for uint256; using SafeERC20 for IERC20Metadata; struct InitParams { ConditionID conditionId; uint256 haltTime; uint256 fee; uint256[] fairPriceDecimals; uint128 minPriceDecimal; } uint256 private constant PRECISION_DECIMALS = AmmMath.PRECISION_DECIMALS; uint256 public constant ONE_DECIMAL = AmmMath.ONE_DECIMAL; IConditionalTokens public conditionalTokens; ConditionID public conditionId; uint256 public haltTime; uint128 public feeDecimal; uint128 public minInvestment; /// @dev The address that is allowed to update target balances address internal priceOracle; address internal conditionOracle; /// @dev minimum acceptable price for any token. uint128 public minPriceDecimal; /// @dev Fair prices of each token normalized to ONE_DECIMAL uint256[] private fairPriceDecimals; /// @dev Conditional token ERC1155 ids for different outcomes uint256[] public positionIds; /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } function initialize(MarketAddressParams calldata addresses, InitParams calldata params) public initializer { __ChildFundingPool_init(addresses.parentPool); __FundingPool_init(addresses.collateralToken); __ERC1155Receiver_init(); conditionalTokens = addresses.conditionalTokens; conditionId = params.conditionId; haltTime = params.haltTime; if (isHalted()) revert MarketHalted(); // Check collateral decimals are not too big uint256 collateralDecimals = collateralToken.decimals(); uint256 oneCollateral = 10 ** collateralDecimals; if (oneCollateral >= type(uint128).max) revert ExcessiveCollateralDecimals(); // Check if fee makes sense. It has to be < 1.0 if (params.fee >= oneCollateral) revert InvalidFee(); if (params.fee > 0) { // Set the minInvestment such that fee will always be non-zero minInvestment = uint128(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(uint128).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 uint128, since it is at most 10 ** PRECISION_DECIMALS if (collateralDecimals < PRECISION_DECIMALS) { feeDecimal = uint128(params.fee * (10 ** (PRECISION_DECIMALS - collateralDecimals))); } else if (collateralDecimals > PRECISION_DECIMALS) { feeDecimal = uint128(params.fee / (10 ** (collateralDecimals - PRECISION_DECIMALS))); } else { feeDecimal = uint128(params.fee); } priceOracle = addresses.priceOracle; conditionOracle = addresses.conditionOracle; positionIds = conditionalTokens.getPositionIds(collateralToken, conditionId); _updateFairPrices(params.fairPriceDecimals); _updateMinPrice(params.minPriceDecimal); } /// @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(); (collateralRemoved, sendAmounts) = _calcRemoveFunding(sharesToBurn); _burnSharesOf(ownerAndReceiver, sharesToBurn); uint256 outcomeSlotCount = positionIds.length; 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); 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) public returns (uint256 collateral, uint256[] memory sendAmounts) { address funder = _msgSender(); (collateral, sendAmounts) = _calcRemoveFunding(sharesToBurn); _burnSharesOf(funder, sharesToBurn); collateralToken.safeTransfer(funder, collateral); conditionalTokens.safeBatchTransferFrom(address(this), funder, positionIds, 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()); } /// @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); } /// @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 Update the externally known fair prices for tokens. Sum must equal ONE_DECIMAL. /// @param _fairPriceDecimals array of values of fair prices for the tokens function updateFairPrices(uint256[] calldata _fairPriceDecimals) external { if (_msgSender() != priceOracle) revert MustBeCalledByOracle(); _updateFairPrices(_fairPriceDecimals); } /// @notice Update the minimum price to give for any one outcome token /// @param _minPriceDecimal decimal price < 1.0 function updateMinPrice(uint128 _minPriceDecimal) external { if (_msgSender() != priceOracle) revert MustBeCalledByOracle(); _updateMinPrice(_minPriceDecimal); } /// @inheritdoc IUpdateHaltTime function updateHaltTime(uint256 _haltTime) external { if (_msgSender() != conditionOracle) revert MustBeCalledByOracle(); if (_haltTime > haltTime) revert InvalidHaltTime(); haltTime = _haltTime; } /// @notice Return the current fair prices used by the market, normalized to ONE_DECIMAL function getFairPrices() external view returns (uint256[] memory) { return fairPriceDecimals; } /// @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 = getTargetBalance(); return AmmMath.calcSpontaneousPricesV3( targetContext.target, targetContext.globalReserves, minPriceDecimal, targetContext.balances, fairPriceDecimals ); } function _updateFairPrices(uint256[] calldata _fairPriceDecimals) private { if (_fairPriceDecimals.length != positionIds.length) revert InvalidPrices(); // When updating the price, it’s important to check if the haltTime has // been reached - traders can no longer place trades after that, so it // is unfair to change price at that point. // // However isHalted() also includes a check whether the condition has // been resolved. This check is redundant because updating a price after // the condition has already been resolved has no effect - the payouts // have already been determined. // // To optimize gas usage, we actually don't need to check if the // condition is resolved or not, only the halt time. // // Finally, because of race conditions between halt time and when the // price oracle submits the last price updates, this may trigger. If // this was a revert, then an entire batch would be reverted. It is // simpler to just ignore the price update. if (block.timestamp >= haltTime) return; uint256 total = _fairPriceDecimals.sum(); if (total != ONE_DECIMAL) revert InvalidPrices(); fairPriceDecimals = _fairPriceDecimals; emit MarketPricesUpdated(fairPriceDecimals); } function _updateMinPrice(uint128 _minPriceDecimal) private { if (_minPriceDecimal >= ONE_DECIMAL) revert InvalidPrices(); minPriceDecimal = _minPriceDecimal; emit MarketMinPriceUpdated(minPriceDecimal); } function getPoolValue() public view returns (uint256) { return AmmMath.calcPoolValue(getPoolBalances(), fairPriceDecimals, reserves()); } /// @inheritdoc IFundingPoolV1 function addFundingFor(address receiver, uint256 collateralAdded) public returns (uint256 sharesMinted) { if (isHalted()) revert MarketHalted(); 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) public returns (uint256 outcomeTokensBought, uint256 feeAmount, uint256[] memory spontaneousPrices) { if (isHalted()) revert MarketHalted(); if (investmentAmount < minInvestment) revert InvalidInvestmentAmount(); feeAmount = (investmentAmount * feeDecimal) / ONE_DECIMAL; uint256 investmentMinusFees = investmentAmount - feeAmount; uint256 tokensToMint; AmmMath.ParentOperations memory parentOps; (outcomeTokensBought, tokensToMint, spontaneousPrices, parentOps) = _calcBuyAmount(investmentMinusFees, outcomeIndex); 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); _retainFees(feeAmount); if (tokensToMint > 0) { // We need to mint some tokens splitPositionThroughAllConditions(tokensToMint); } conditionalTokens.safeTransferFrom(address(this), receiver, positionIds[outcomeIndex], outcomeTokensBought, ""); // 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; } /// @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) public view returns (uint256 outcomeTokensBought, uint256 feeAmount, uint256[] memory spontaneousPrices) { feeAmount = (investmentAmount * feeDecimal) / ONE_DECIMAL; uint256 tokensMinted = investmentAmount - feeAmount; (outcomeTokensBought,, spontaneousPrices,) = _calcBuyAmount(tokensMinted, indexOut); } /// @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: /// - If no parent pool, then all collateral is internal reserves of the /// market. The minimal amount of collateral is used to mint any new tokens /// in order to fulfil the order. At the end of a buy operation at least one /// of the token balances is 0, otherwise some amount would be mergeable. /// Majority of value in the pool should be kept as collateral. /// - 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. /// - When a parent pool is involved, we can request and return funding as /// needed to fulfil orders. The parent pool has a certain allowance that /// the algorithm can assume it will have access to. /// - When ONLY a parent pool is providing funding, then at the very start, /// no collateral reserves are available in the market itself, and no tokens /// are available. When a purchase occurs, just enough collateral is /// requested from the parent to mint enough tokens to give back to the /// buyer. 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 /// - In the hybrid case, where there are some regular funders, and a parent /// pool funder, there is a blend between the above behaviors proportional /// to the shares held by the parent and the funders. In particular the /// excess collateral given by the user is shared between the funders and /// the parent. /// @param investmentMinusFees Amount of collateral token invested without fees /// @param indexOut Position index of the condition. /// @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 spontaneousPrices pries of tokens after the buy /// @return parentOps operations to perform with parent funding function _calcBuyAmount(uint256 investmentMinusFees, uint256 indexOut) private view returns ( uint256 outcomeTokensBought, uint256 tokensToMint, uint256[] memory spontaneousPrices, AmmMath.ParentOperations memory parentOps ) { AmmMath.TargetContext memory targetContext = getTargetBalance(); (uint256 tokensExchanged, uint256 newPoolValue) = AmmMath.calcBuyAmountV3( investmentMinusFees, indexOut, targetContext.target, targetContext.globalReserves, minPriceDecimal, targetContext.balances, fairPriceDecimals ); AmmMath.BuyContext memory buyContext = AmmMath.BuyContext(investmentMinusFees, tokensExchanged, newPoolValue); address parent = getParentPool(); AmmMath.ShareContext memory shareContext = AmmMath.ShareContext(balanceOf(parent), totalSupply()); (outcomeTokensBought, tokensToMint, parentOps) = AmmMath.calcMarketPoolChanges(indexOut, targetContext, buyContext, shareContext); spontaneousPrices = AmmMath.calcSpontaneousPricesV3( targetContext.target, targetContext.globalReserves, minPriceDecimal, 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(IUpdateHaltTime).interfaceId || interfaceId == type(IFundingPoolV1).interfaceId || interfaceId == type(IFundingPoolV1_1).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 block.timestamp >= haltTime || conditionalTokens.isResolved(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) { address[] memory thises = new address[](positionIds.length); for (uint256 i = 0; i < positionIds.length; i++) { thises[i] = address(this); } return conditionalTokens.balanceOfBatch(thises, positionIds); } /// @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 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 localReserves = reserves(); targetContext = AmmMath.TargetContext({ target: getTotalFunderCostBasis(), globalReserves: localReserves, localReserves: localReserves, balances: getPoolBalances() }); // 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; } } function _afterFeesWithdrawn(address funder, uint256 collateralRemovedFromFees) internal virtual override { address parent = getParentPool(); if (funder == parent) { IParentFundingPoolV1(parent).feesReturned(collateralRemovedFromFees); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; import { AmmErrors } from "./AmmErrors.sol"; import { FundingErrors } from "../funding/FundingErrors.sol"; interface MarketErrors is AmmErrors, FundingErrors { error MarketHalted(); error MarketUndecided(); error MustBeCalledByOracle(); // Buy error InvalidInvestmentAmount(); error MinimumBuyAmountNotReached(); // Sell error InvalidReturnAmount(); error MaximumSellAmountExceeded(); error InvestmentDrainsPool(); error OperationNotSupported(); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; 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); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; // 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; } function hasNonzeroEntries(uint256[] memory values) internal pure returns (bool) { for (uint256 i = 0; i < values.length; i++) { if (values[i] > 0) return true; } return false; } } /// @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 pragma solidity ^0.8.17; 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.17; import { IConditionalTokens } from "../conditions/IConditionalTokens.sol"; import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; struct MarketAddressParams { IConditionalTokens conditionalTokens; IERC20Metadata collateralToken; address parentPool; address priceOracle; address conditionOracle; }
// 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.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.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 // 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.17; interface IUpdateHaltTime { /// @dev new haltTime is after old haltTime error InvalidHaltTime(); event HaltTimeUpdated(uint256 haltTime); /// @notice Update the halt time of a contract /// @dev Should be in the past relative to current halt time /// @param haltTime epoch seconds timestamp of halt time function updateHaltTime(uint256 haltTime) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; 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 { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.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; uint256 private feePoolWeight; mapping(address => uint256) private withdrawnFees; uint256 private totalWithdrawnFees; /// @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; /// @inheritdoc IFundingPoolV1 function withdrawFees(address funder) public returns (uint256 collateralRemovedFromFees) { collateralRemovedFromFees = feesWithdrawableBy(funder); if (collateralRemovedFromFees > 0) { withdrawnFees[funder] += collateralRemovedFromFees; totalWithdrawnFees = totalWithdrawnFees + collateralRemovedFromFees; collateralToken.safeTransfer(funder, collateralRemovedFromFees); emit FeesWithdrawn(funder, collateralRemovedFromFees); _afterFeesWithdrawn(funder, collateralRemovedFromFees); } } /// @inheritdoc IFundingPoolV1 function feesWithdrawableBy(address account) public view returns (uint256) { uint256 rawAmount = (feePoolWeight * balanceOf(account)) / totalSupply(); // Sometimes when feePoolWeight is not exactly divisible, the truncation // during division may result in rawAmount being 1 less than // `withdrawnFees`. This is ok, and that descrepancy will fix itself as // more users remove their shares/fees. assert(rawAmount + 1 >= withdrawnFees[account]); rawAmount = Math.max(rawAmount, withdrawnFees[account]); return rawAmount - withdrawnFees[account]; } /// @inheritdoc IFundingPoolV1 function collectedFees() public view returns (uint256) { return feePoolWeight - totalWithdrawnFees; } /// @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; } /// @notice Computes the fees when positions are bought, sold or transferred function _beforeTokenTransfer(address from, address to, uint256 amount) internal override { if (from != address(0)) { // LP tokens being transferred away from a funder - any fees that // have accumulated so far due to trading activity should be given // to the original owner for the period of time he held the LP // tokens withdrawFees(from); } // `supply` includes `amount` during: // - funder to funder transfer // - burning // `supply` does _not_ include `amount` during: // - minting uint256 supply = totalSupply(); // Fee pool weight proportional to the shares of LP total supply. This // proportion of fee pool weight will be transferred between funders, so // that their claim to the fees does not increase/descrease // instantaneously. uint256 withdrawnFeesTransfer; if (from != address(0)) { // Transferring lp shares away from a funder withdrawnFeesTransfer = (withdrawnFees[from] * amount) / balanceOf(from); withdrawnFees[from] = withdrawnFees[from] - withdrawnFeesTransfer; totalWithdrawnFees = totalWithdrawnFees - withdrawnFeesTransfer; } else { // minting new lp shares. Grow the weight of the fee pool // proportionally to the LP total supply // slither-disable-next-line dangerous-strict-equalities withdrawnFeesTransfer = supply == 0 ? feePoolWeight : (feePoolWeight * amount) / supply; feePoolWeight = feePoolWeight + withdrawnFeesTransfer; } if (to != address(0)) { // Transferring lp shares to a funder withdrawnFees[to] = withdrawnFees[to] + withdrawnFeesTransfer; totalWithdrawnFees = totalWithdrawnFees + withdrawnFeesTransfer; } else { // burning lp shares. Shrink the weight of the fee pool // proportionally to the LP total supply feePoolWeight = feePoolWeight - withdrawnFeesTransfer; } } /// @dev Sets aside some collateral as fees function _retainFees(uint256 collateralFees) internal { if (collateralFees > reserves()) revert FeesExceedReserves(); feePoolWeight = feePoolWeight + collateralFees; emit FeesRetained(collateralFees); } /// @dev implement this to get a callback when fees are transferred // solhint-disable-next-line no-empty-blocks function _afterFeesWithdrawn(address funder, uint256 collateralRemovedFromFees) internal virtual { } /// @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.17; 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 private 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) && !IParentFundingPoolV1(parentPool).supportsInterface(PARENT_FUNDING_POOL_INTERFACE_ID) ) { revert NotAParentPool(parentPool); } _parent = parentPool; emit ParentPoolAdded(parentPool); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; 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 exceed uint256. UD60x18 internal constant MAX_EXPONENT = UD60x18.wrap(133084258667509499440); /// @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. /// @return poolValue total sum of value of all tokens function calcPoolValue(uint256[] memory balances, uint256[] memory fairPriceDecimals) internal pure returns (uint256 poolValue) { if (fairPriceDecimals.length != balances.length) revert AmmErrors.InvalidPrices(); 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. /// @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 /// @param minPriceDecimal minimal price to use for output tokens /// @return tokensOutDecimal quantity of tokens resulting from the exchange function calcElementwiseFairAmount( uint256 tokensMintedDecimal, uint256 fairPriceInDecimal, uint256 fairPriceOutDecimal, uint256 minPriceDecimal ) internal pure returns (uint256 tokensOutDecimal) { fairPriceOutDecimal = Math.max(fairPriceOutDecimal, minPriceDecimal); 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 /// @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 /// @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 minPriceDecimal, uint256[] memory balances, uint256[] memory fairPriceDecimals ) internal pure returns (uint256 tokensOut, uint256 newPoolValue) { if (indexOut >= balances.length) revert AmmErrors.InvalidOutcomeIndex(); if (fairPriceDecimals.length != balances.length) revert AmmErrors.InvalidPrices(); 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], minPriceDecimal ); 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. /// @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 /// @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 minPriceDecimal, uint256[] memory balances, uint256[] memory fairPriceDecimals ) internal pure returns (uint256[] memory spontaneousPriceDecimals) { if (fairPriceDecimals.length != balances.length) revert AmmErrors.InvalidPrices(); 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], minPriceDecimal ); } // 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 ShareContext { uint256 parentShares; uint256 totalShares; } 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; /// @dev collateral available for minting just in the market itself. uint256 localReserves; uint256[] balances; } struct BuyContext { uint256 investmentMinusFees; uint256 tokensExchanged; uint256 newPoolValue; } /// @dev Calculate how the state of the Amm Pool should change as a result of a buy order. /// @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 shareContext information on liquidity 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, TargetContext memory targetContext, BuyContext memory buyContext, ShareContext memory shareContext ) internal pure returns (uint256 outcomeTokensBought, uint256 tokensToMint, ParentOperations memory parentOps) { parentOps = ParentOperations(0, 0, 0); outcomeTokensBought = buyContext.tokensExchanged + buyContext.investmentMinusFees; tokensToMint = outcomeTokensBought.subClamp(targetContext.balances[indexOut]); uint256 localReservesAfterPayment = targetContext.localReserves + buyContext.investmentMinusFees; // check if we don't have enough tokens, or too many if (tokensToMint >= localReservesAfterPayment) { // If collateral is needed from the parent to mint tokens, that // implies that all funder collateral will be tied up in tokens. unchecked { parentOps.collateralToRequestFromParent = tokensToMint - localReservesAfterPayment; } targetContext.localReserves = 0; } else { // In this case all parent funding is tied up in tokens, and // potentially some collateral is still in reserves from other // funders. None of the collateral in reserves before the buy // operation belongs to the parent. // The leftover collateral from the buyer's investment is // distributed between local reserves, and back to the parent uint256 investmentLeftOver; unchecked { // Min needed here because parent is only entitled to get // collateral back from investment, not local reserves from // individual contributors. investmentLeftOver = Math.min(localReservesAfterPayment - tokensToMint, buyContext.investmentMinusFees); } assert(shareContext.totalShares > 0); if (shareContext.parentShares > 0) { uint256 tokenAndLocalReservesValue = (buyContext.newPoolValue + targetContext.localReserves - targetContext.globalReserves); // parent is eligible to get only its portion of leftover collateral parentOps.collateralToReturnToParent = (investmentLeftOver * shareContext.parentShares) / shareContext.totalShares; // number of shares to return depends on proportion of the collateral we are returning to value in market parentOps.sharesToBurnOfParent = (parentOps.collateralToReturnToParent * shareContext.totalShares) / tokenAndLocalReservesValue; } // calculate new local reserves after minting and returns to parent targetContext.localReserves = localReservesAfterPayment - tokensToMint - parentOps.collateralToReturnToParent; } // Update TargetContext so it reflects the new state of the market targetContext.globalReserves = targetContext.globalReserves + buyContext.investmentMinusFees - tokensToMint; for (uint256 i = 0; i < targetContext.balances.length; i++) { targetContext.balances[i] += tokensToMint; if (i == indexOut) { targetContext.balances[i] -= outcomeTokensBought; } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; 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.17; interface AmmErrors { error InvalidOutcomeIndex(); error InvalidPrices(); error NoLiquidityAvailable(); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; 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 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 // 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.17; 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))); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; 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(); /// @dev using unapproved ERC20 token with protocol error InvalidERC20(); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; 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.17; 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 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 // 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 // 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 pragma solidity ^0.8.17; 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.17; 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.17; 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 pragma solidity >=0.8.13; 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 // 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 pragma solidity >=0.8.13; 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 { PRBMath_UD60x18_IntoSD1x18_Overflow, PRBMath_UD60x18_IntoUD2x18_Overflow, PRBMath_UD60x18_IntoSD59x18_Overflow, PRBMath_UD60x18_IntoUint128_Overflow, PRBMath_UD60x18_IntoUint40_Overflow } from "./Errors.sol"; import { UD60x18 } from "./ValueType.sol"; /// @notice Casts an 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 PRBMath_UD60x18_IntoSD1x18_Overflow(x); } result = SD1x18.wrap(int64(uint64(xUint))); } /// @notice Casts an 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 PRBMath_UD60x18_IntoUD2x18_Overflow(x); } result = UD2x18.wrap(uint64(xUint)); } /// @notice Casts an 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 PRBMath_UD60x18_IntoSD59x18_Overflow(x); } result = SD59x18.wrap(int256(xUint)); } /// @notice Casts an UD60x18 number into uint128. /// @dev This is basically a functional alias for the `unwrap` function. function intoUint256(UD60x18 x) pure returns (uint256 result) { result = UD60x18.unwrap(x); } /// @notice Casts an 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 PRBMath_UD60x18_IntoUint128_Overflow(x); } result = uint128(xUint); } /// @notice Casts an 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 PRBMath_UD60x18_IntoUint40_Overflow(x); } result = uint40(xUint); } /// @notice Alias for the `wrap` function. function ud(uint256 x) pure returns (UD60x18 result) { result = UD60x18.wrap(x); } /// @notice Alias for the `wrap` function. function ud60x18(uint256 x) pure returns (UD60x18 result) { result = UD60x18.wrap(x); } /// @notice Unwraps an UD60x18 number into uint256. function unwrap(UD60x18 x) pure returns (uint256 result) { result = UD60x18.unwrap(x); } /// @notice Wraps an 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.13; import { UD60x18 } from "./ValueType.sol"; /// @dev Euler's number as an UD60x18 number. UD60x18 constant E = UD60x18.wrap(2_718281828459045235); /// @dev Half the UNIT number. uint256 constant uHALF_UNIT = 0.5e18; UD60x18 constant HALF_UNIT = UD60x18.wrap(uHALF_UNIT); /// @dev log2(10) as an UD60x18 number. uint256 constant uLOG2_10 = 3_321928094887362347; UD60x18 constant LOG2_10 = UD60x18.wrap(uLOG2_10); /// @dev log2(e) as an UD60x18 number. uint256 constant uLOG2_E = 1_442695040888963407; UD60x18 constant LOG2_E = UD60x18.wrap(uLOG2_E); /// @dev The maximum value an UD60x18 number can have. uint256 constant uMAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935; UD60x18 constant MAX_UD60x18 = UD60x18.wrap(uMAX_UD60x18); /// @dev The maximum whole value an UD60x18 number can have. uint256 constant uMAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000; UD60x18 constant MAX_WHOLE_UD60x18 = UD60x18.wrap(uMAX_WHOLE_UD60x18); /// @dev PI as an UD60x18 number. UD60x18 constant PI = UD60x18.wrap(3_141592653589793238); /// @dev The unit amount that implies how many trailing decimals can be represented. uint256 constant uUNIT = 1e18; UD60x18 constant UNIT = UD60x18.wrap(uUNIT); /// @dev Zero as an UD60x18 number. UD60x18 constant ZERO = UD60x18.wrap(0);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import { uMAX_UD60x18, uUNIT } from "./Constants.sol"; import { PRBMath_UD60x18_Convert_Overflow } from "./Errors.sol"; import { UD60x18 } from "./ValueType.sol"; /// @notice Converts an UD60x18 number to a simple integer by dividing it by `UNIT`. Rounds towards zero in the process. /// @dev Rounds down in the process. /// @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` divided by `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); } } /// @notice Alias for the `convert` function defined above. /// @dev Here for backward compatibility. Will be removed in V4. function fromUD60x18(UD60x18 x) pure returns (uint256 result) { result = convert(x); } /// @notice Alias for the `convert` function defined above. /// @dev Here for backward compatibility. Will be removed in V4. function toUD60x18(uint256 x) pure returns (UD60x18 result) { result = convert(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import { UD60x18 } from "./ValueType.sol"; /// @notice Emitted when ceiling a number overflows UD60x18. error PRBMath_UD60x18_Ceil_Overflow(UD60x18 x); /// @notice Emitted when converting a basic integer to the fixed-point format overflows UD60x18. error PRBMath_UD60x18_Convert_Overflow(uint256 x); /// @notice Emitted when taking the natural exponent of a base greater than 133.084258667509499441. error PRBMath_UD60x18_Exp_InputTooBig(UD60x18 x); /// @notice Emitted when taking the binary exponent of a base greater than 192. error PRBMath_UD60x18_Exp2_InputTooBig(UD60x18 x); /// @notice Emitted when taking the geometric mean of two numbers and multiplying them overflows UD60x18. error PRBMath_UD60x18_Gm_Overflow(UD60x18 x, UD60x18 y); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in SD1x18. error PRBMath_UD60x18_IntoSD1x18_Overflow(UD60x18 x); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in SD59x18. error PRBMath_UD60x18_IntoSD59x18_Overflow(UD60x18 x); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in UD2x18. error PRBMath_UD60x18_IntoUD2x18_Overflow(UD60x18 x); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint128. error PRBMath_UD60x18_IntoUint128_Overflow(UD60x18 x); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint40. error PRBMath_UD60x18_IntoUint40_Overflow(UD60x18 x); /// @notice Emitted when taking the logarithm of a number less than 1. error PRBMath_UD60x18_Log_InputTooSmall(UD60x18 x); /// @notice Emitted when calculating the square root overflows UD60x18. error PRBMath_UD60x18_Sqrt_Overflow(UD60x18 x);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import { unwrap, 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(unwrap(x) + unwrap(y)); } /// @notice Implements the AND (&) bitwise operation in the UD60x18 type. function and(UD60x18 x, uint256 bits) pure returns (UD60x18 result) { result = wrap(unwrap(x) & bits); } /// @notice Implements the equal operation (==) in the UD60x18 type. function eq(UD60x18 x, UD60x18 y) pure returns (bool result) { result = unwrap(x) == unwrap(y); } /// @notice Implements the greater than operation (>) in the UD60x18 type. function gt(UD60x18 x, UD60x18 y) pure returns (bool result) { result = unwrap(x) > unwrap(y); } /// @notice Implements the greater than or equal to operation (>=) in the UD60x18 type. function gte(UD60x18 x, UD60x18 y) pure returns (bool result) { result = unwrap(x) >= unwrap(y); } /// @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 = unwrap(x) == 0; } /// @notice Implements the left shift operation (<<) in the UD60x18 type. function lshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) { result = wrap(unwrap(x) << bits); } /// @notice Implements the lower than operation (<) in the UD60x18 type. function lt(UD60x18 x, UD60x18 y) pure returns (bool result) { result = unwrap(x) < unwrap(y); } /// @notice Implements the lower than or equal to operation (<=) in the UD60x18 type. function lte(UD60x18 x, UD60x18 y) pure returns (bool result) { result = unwrap(x) <= unwrap(y); } /// @notice Implements the checked modulo operation (%) in the UD60x18 type. function mod(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(unwrap(x) % unwrap(y)); } /// @notice Implements the not equal operation (!=) in the UD60x18 type function neq(UD60x18 x, UD60x18 y) pure returns (bool result) { result = unwrap(x) != unwrap(y); } /// @notice Implements the OR (|) bitwise operation in the UD60x18 type. function or(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(unwrap(x) | unwrap(y)); } /// @notice Implements the right shift operation (>>) in the UD60x18 type. function rshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) { result = wrap(unwrap(x) >> bits); } /// @notice Implements the checked subtraction operation (-) in the UD60x18 type. function sub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(unwrap(x) - unwrap(y)); } /// @notice Implements the unchecked addition operation (+) in the UD60x18 type. function uncheckedAdd(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { unchecked { result = wrap(unwrap(x) + unwrap(y)); } } /// @notice Implements the unchecked subtraction operation (-) in the UD60x18 type. function uncheckedSub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { unchecked { result = wrap(unwrap(x) - unwrap(y)); } } /// @notice Implements the XOR (^) bitwise operation in the UD60x18 type. function xor(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(unwrap(x) ^ unwrap(y)); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import { msb, mulDiv, mulDiv18, prbExp2, prbSqrt } from "../Common.sol"; import { unwrap, wrap } from "./Casting.sol"; import { uHALF_UNIT, uLOG2_10, uLOG2_E, uMAX_UD60x18, uMAX_WHOLE_UD60x18, UNIT, uUNIT, ZERO } from "./Constants.sol"; import { PRBMath_UD60x18_Ceil_Overflow, PRBMath_UD60x18_Exp_InputTooBig, PRBMath_UD60x18_Exp2_InputTooBig, PRBMath_UD60x18_Gm_Overflow, PRBMath_UD60x18_Log_InputTooSmall, PRBMath_UD60x18_Sqrt_Overflow } from "./Errors.sol"; import { UD60x18 } from "./ValueType.sol"; /*////////////////////////////////////////////////////////////////////////// MATHEMATICAL FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ /// @notice Calculates the arithmetic average of x and y, rounding down. /// /// @dev Based on the formula: /// /// $$ /// avg(x, y) = (x & y) + ((xUint ^ yUint) / 2) /// $$ // /// In English, what this formula does is: /// /// 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 /// /// @param x The first operand as an UD60x18 number. /// @param y The second operand as an UD60x18 number. /// @return result The arithmetic average as an UD60x18 number. function avg(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { uint256 xUint = unwrap(x); uint256 yUint = unwrap(y); unchecked { result = wrap((xUint & yUint) + ((xUint ^ yUint) >> 1)); } } /// @notice Yields the smallest whole UD60x18 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 least number greater than or equal to x, as an UD60x18 number. function ceil(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = unwrap(x); if (xUint > uMAX_WHOLE_UD60x18) { revert PRBMath_UD60x18_Ceil_Overflow(x); } assembly ("memory-safe") { // Equivalent to "x % UNIT" but faster. let remainder := mod(x, uUNIT) // Equivalent to "UNIT - remainder" but faster. let delta := sub(uUNIT, remainder) // Equivalent to "x + delta * (remainder > 0 ? 1 : 0)" but faster. result := add(x, mul(delta, gt(remainder, 0))) } } /// @notice Divides two UD60x18 numbers, returning a new UD60x18 number. Rounds towards zero. /// /// @dev Uses `mulDiv` to enable overflow-safe multiplication and division. /// /// Requirements: /// - The denominator cannot be zero. /// /// @param x The numerator as an UD60x18 number. /// @param y The denominator as an UD60x18 number. /// @param result The quotient as an UD60x18 number. function div(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(mulDiv(unwrap(x), uUNIT, unwrap(y))); } /// @notice Calculates the natural exponent of x. /// /// @dev Based on the formula: /// /// $$ /// e^x = 2^{x * log_2{e}} /// $$ /// /// Requirements: /// - All from `log2`. /// - x must be less than 133.084258667509499441. /// /// @param x The exponent as an UD60x18 number. /// @return result The result as an UD60x18 number. function exp(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = unwrap(x); // Without this check, the value passed to `exp2` would be greater than 192. if (xUint >= 133_084258667509499441) { revert PRBMath_UD60x18_Exp_InputTooBig(x); } unchecked { // We do the fixed-point multiplication inline rather than via the `mul` function 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 192 or less. /// - The result must fit within `MAX_UD60x18`. /// /// @param x The exponent as an UD60x18 number. /// @return result The result as an UD60x18 number. function exp2(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = unwrap(x); // Numbers greater than or equal to 2^192 don't fit within the 192.64-bit format. if (xUint >= 192e18) { revert 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 `prbExp2` function, which uses the 192.64-bit fixed-point number representation. result = wrap(prbExp2(x_192x64)); } /// @notice Yields the greatest whole UD60x18 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. /// @param x The UD60x18 number to floor. /// @param result The greatest integer less than or equal to x, as an UD60x18 number. function floor(UD60x18 x) pure returns (UD60x18 result) { assembly ("memory-safe") { // Equivalent to "x % UNIT" but faster. let remainder := mod(x, uUNIT) // Equivalent to "x - remainder * (remainder > 0 ? 1 : 0)" but faster. result := sub(x, mul(remainder, gt(remainder, 0))) } } /// @notice Yields the excess beyond the floor of x. /// @dev Based on the odd function definition 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 an UD60x18 number. 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 within `MAX_UD60x18`, lest it overflows. /// /// @param x The first operand as an UD60x18 number. /// @param y The second operand as an UD60x18 number. /// @return result The result as an UD60x18 number. function gm(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { uint256 xUint = unwrap(x); uint256 yUint = unwrap(y); 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 PRBMath_UD60x18_Gm_Overflow(x, y); } // We don't need to multiply the result by `UNIT` here because the x*y product had picked up a factor of `UNIT` // during multiplication. See the comments in the `prbSqrt` function. result = wrap(prbSqrt(xyUint)); } } /// @notice Calculates 1 / x, rounding toward zero. /// /// @dev Requirements: /// - x cannot be zero. /// /// @param x The UD60x18 number for which to calculate the inverse. /// @return result The inverse as an UD60x18 number. function inv(UD60x18 x) pure returns (UD60x18 result) { unchecked { // 1e36 is UNIT * UNIT. result = wrap(1e36 / unwrap(x)); } } /// @notice Calculates the natural logarithm of x. /// /// @dev Based on the formula: /// /// $$ /// ln{x} = log_2{x} / log_2{e}$$. /// $$ /// /// Requirements: /// - All from `log2`. /// /// Caveats: /// - All from `log2`. /// - This doesn't return exactly 1 for 2.718281828459045235, for that more fine-grained precision is needed. /// /// @param x The UD60x18 number for which to calculate the natural logarithm. /// @return result The natural logarithm as an UD60x18 number. function ln(UD60x18 x) pure returns (UD60x18 result) { unchecked { // We do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value // that `log2` can return is 196.205294292027477728. result = wrap((unwrap(log2(x)) * uUNIT) / uLOG2_E); } } /// @notice Calculates the common logarithm of x. /// /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common /// logarithm based on the formula: /// /// $$ /// log_{10}{x} = log_2{x} / log_2{10} /// $$ /// /// Requirements: /// - All from `log2`. /// /// Caveats: /// - All from `log2`. /// /// @param x The UD60x18 number for which to calculate the common logarithm. /// @return result The common logarithm as an UD60x18 number. function log10(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = unwrap(x); if (xUint < uUNIT) { revert PRBMath_UD60x18_Log_InputTooSmall(x); } // Note that the `mul` in this assembly block is the assembly multiplication operation, not the 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 (unwrap(result) == uMAX_UD60x18) { unchecked { // Do the fixed-point division inline to save gas. result = wrap((unwrap(log2(x)) * uUNIT) / uLOG2_10); } } } /// @notice Calculates the binary logarithm of x. /// /// @dev Based on the iterative approximation algorithm. /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Requirements: /// - x must be greater than or equal to UNIT, otherwise the result would be negative. /// /// Caveats: /// - The results are nor perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation. /// /// @param x The UD60x18 number for which to calculate the binary logarithm. /// @return result The binary logarithm as an UD60x18 number. function log2(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = unwrap(x); if (xUint < uUNIT) { revert PRBMath_UD60x18_Log_InputTooSmall(x); } unchecked { // Calculate the integer part of the logarithm, add it to the result and finally calculate y = x * 2^(-n). uint256 n = msb(xUint / uUNIT); // This is the integer part of the logarithm as an UD60x18 number. The operation can't overflow because n // n is maximum 255 and UNIT is 1e18. uint256 resultUint = n * uUNIT; // This is $y = x * 2^{-n}$. uint256 y = xUint >> n; // If y is 1, the fractional part is zero. if (y == uUNIT) { return wrap(resultUint); } // Calculate the fractional part via the iterative approximation. // The "delta.rshift(1)" part is equivalent to "delta /= 2", but shifting bits is faster. uint256 DOUBLE_UNIT = 2e18; for (uint256 delta = uHALF_UNIT; delta > 0; delta >>= 1) { y = (y * y) / uUNIT; // Is y^2 > 2 and so in the range [2,4)? if (y >= DOUBLE_UNIT) { // Add the 2^{-m} factor to the logarithm. resultUint += delta; // Corresponds to z/2 on Wikipedia. y >>= 1; } } result = wrap(resultUint); } } /// @notice Multiplies two UD60x18 numbers together, returning a new UD60x18 number. /// @dev See the documentation for the `Common.mulDiv18` function. /// @param x The multiplicand as an UD60x18 number. /// @param y The multiplier as an UD60x18 number. /// @return result The product as an UD60x18 number. function mul(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { result = wrap(mulDiv18(unwrap(x), unwrap(y))); } /// @notice Raises x to the power of y. /// /// @dev Based on the formula: /// /// $$ /// x^y = 2^{log_2{x} * y} /// $$ /// /// Requirements: /// - All from `exp2`, `log2` and `mul`. /// /// Caveats: /// - All from `exp2`, `log2` and `mul`. /// - Assumes 0^0 is 1. /// /// @param x Number to raise to given power y, as an UD60x18 number. /// @param y Exponent to raise x to, as an UD60x18 number. /// @return result x raised to power y, as an UD60x18 number. function pow(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) { uint256 xUint = unwrap(x); uint256 yUint = unwrap(y); if (xUint == 0) { result = yUint == 0 ? UNIT : ZERO; } else { if (yUint == uUNIT) { result = x; } else { result = exp2(mul(log2(x), y)); } } } /// @notice Raises x (an UD60x18 number) to the power y (unsigned basic integer) using the famous algorithm /// "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring /// /// Requirements: /// - The result must fit within `MAX_UD60x18`. /// /// Caveats: /// - All from "Common.mulDiv18". /// - Assumes 0^0 is 1. /// /// @param x The base as an UD60x18 number. /// @param y The exponent as an uint256. /// @return result The result as an UD60x18 number. function powu(UD60x18 x, uint256 y) pure returns (UD60x18 result) { // Calculate the first iteration of the loop in advance. uint256 xUint = unwrap(x); uint256 resultUint = y & 1 > 0 ? xUint : uUNIT; // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster. for (y >>= 1; y > 0; y >>= 1) { xUint = mulDiv18(xUint, xUint); // Equivalent to "y % 2 == 1" but faster. if (y & 1 > 0) { resultUint = mulDiv18(resultUint, xUint); } } result = wrap(resultUint); } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Requirements: /// - x must be less than `MAX_UD60x18` divided by `UNIT`. /// /// @param x The UD60x18 number for which to calculate the square root. /// @return result The result as an UD60x18 number. function sqrt(UD60x18 x) pure returns (UD60x18 result) { uint256 xUint = unwrap(x); unchecked { if (xUint > uMAX_UD60x18 / uUNIT) { revert PRBMath_UD60x18_Sqrt_Overflow(x); } // Multiply x by `UNIT` to account for the factor of `UNIT` that is picked up when multiplying two UD60x18 // numbers together (in this case, the two numbers are both the square root). result = wrap(prbSqrt(xUint * uUNIT)); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import "./Casting.sol" as C; import "./Helpers.sol" as H; import "./Math.sol" as M; /// @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 { C.intoSD1x18, C.intoUD2x18, C.intoSD59x18, C.intoUint128, C.intoUint256, C.intoUint40, C.unwrap } for UD60x18 global; /*////////////////////////////////////////////////////////////////////////// MATHEMATICAL FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ /// The global "using for" directive makes the functions in this library callable on the UD60x18 type. using { M.avg, M.ceil, M.div, M.exp, M.exp2, M.floor, M.frac, M.gm, M.inv, M.ln, M.log10, M.log2, M.mul, M.pow, M.powu, M.sqrt } for UD60x18 global; /*////////////////////////////////////////////////////////////////////////// HELPER FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ /// The global "using for" directive makes the functions in this library callable on the UD60x18 type. using { H.add, H.and, H.eq, H.gt, H.gte, H.isZero, H.lshift, H.lt, H.lte, H.mod, H.neq, H.or, H.rshift, H.sub, H.uncheckedAdd, H.uncheckedSub, H.xor } for UD60x18 global;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; /// 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 Emitted when the ending result in the fixed-point version of `mulDiv` would overflow uint256. error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y); /// @notice Emitted when the ending result in `mulDiv` would overflow uint256. error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator); /// @notice Emitted when attempting to run `mulDiv` with one of the inputs `type(int256).min`. error PRBMath_MulDivSigned_InputTooSmall(); /// @notice Emitted when the ending result in the signed version of `mulDiv` would overflow int256. error PRBMath_MulDivSigned_Overflow(int256 x, int256 y); /*////////////////////////////////////////////////////////////////////////// CONSTANTS //////////////////////////////////////////////////////////////////////////*/ /// @dev The maximum value an uint128 number can have. uint128 constant MAX_UINT128 = type(uint128).max; /// @dev The maximum value an uint40 number can have. uint40 constant MAX_UINT40 = type(uint40).max; /// @dev How many trailing decimals can be represented. uint256 constant UNIT = 1e18; /// @dev Largest power of two that is a divisor of `UNIT`. uint256 constant UNIT_LPOTD = 262144; /// @dev The `UNIT` number inverted mod 2^256. uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281; /*////////////////////////////////////////////////////////////////////////// FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ /// @notice Finds the zero-based index of the first one in the binary representation of x. /// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set /// /// Each of the steps in this implementation is equivalent to this high-level code: /// /// ```solidity /// if (x >= 2 ** 128) { /// x >>= 128; /// result += 128; /// } /// ``` /// /// Where 128 is swapped with each respective power of two factor. See the full high-level implementation here: /// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948 /// /// A list of the Yul instructions used below: /// - "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 an uint256. 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 floor(x*y÷denominator) with full precision. /// /// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv. /// /// Requirements: /// - The denominator cannot be zero. /// - The result must fit within uint256. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The multiplicand as an uint256. /// @param y The multiplier as an uint256. /// @param denominator The divisor as an uint256. /// @return result The result as an uint256. 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) } // 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. unchecked { // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 lpotdod = denominator & (~denominator + 1); assembly ("memory-safe") { // Divide denominator by lpotdod. denominator := div(denominator, lpotdod) // Divide [prod1 prod0] by lpotdod. prod0 := div(prod0, lpotdod) // Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one. lpotdod := add(div(sub(0, lpotdod), lpotdod), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * lpotdod; // 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 floor(x*y÷1e18) with full precision. /// /// @dev Variant of `mulDiv` with constant folding, i.e. in which the denominator is always 1e18. Before returning the /// final result, we add 1 if `(x * y) % UNIT >= HALF_UNIT`. Without this adjustment, 6.6e-19 would be truncated to 0 /// instead of being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717. /// /// Requirements: /// - The result must fit within uint256. /// /// Caveats: /// - The body is purposely left uncommented; to understand how this works, see the NatSpec comments in `mulDiv`. /// - It is assumed that the result can never be `type(uint256).max` when x and y solve the following two equations: /// 1. x * y = type(uint256).max * UNIT /// 2. (x * y) % UNIT >= UNIT / 2 /// /// @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. 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 >= UNIT) { revert PRBMath_MulDiv18_Overflow(x, y); } uint256 remainder; assembly ("memory-safe") { remainder := mulmod(x, y, UNIT) } if (prod1 == 0) { unchecked { return prod0 / UNIT; } } assembly ("memory-safe") { 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 floor(x*y÷denominator) with full precision. /// /// @dev An extension of `mulDiv` for signed numbers. Works by computing the signs and the absolute values separately. /// /// Requirements: /// - None of the inputs can be `type(int256).min`. /// - The result must fit within 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. 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 absX; uint256 absY; uint256 absD; unchecked { absX = x < 0 ? uint256(-x) : uint256(x); absY = y < 0 ? uint256(-y) : uint256(y); absD = denominator < 0 ? uint256(-denominator) : uint256(denominator); } // Compute the absolute value of (x*y)÷denominator. The result must fit within int256. uint256 rAbs = mulDiv(absX, absY, absD); if (rAbs > 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") { // This works thanks to two's complement. // "sgt" stands for "signed greater than" and "sub(0,1)" is max uint256. 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(rAbs) : int256(rAbs); } } /// @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. function prbExp2(uint256 x) pure returns (uint256 result) { unchecked { // Start from 0.5 in the 192.64-bit fixed-point format. result = 0x800000000000000000000000000000000000000000000000; // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows // because the initial result is 2^191 and all magic factors are less than 2^65. 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; } } // We're doing two things at the same time: // // 1. Multiply the result by 2^n + 1, where "2^n" is the integer part and the one is added to account for // the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191 // rather than 192. // 2. Convert the result to the unsigned 60.18-decimal fixed-point format. // // This works because 2^(191-ip) = 2^ip / 2^191, where "ip" is the integer part "2^n". result *= UNIT; result >>= (191 - (x >> 64)); } } /// @notice Calculates the square root of x, rounding down if x is not a perfect square. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// Credits to OpenZeppelin for the explanations in code comments below. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The uint256 number for which to calculate the square root. /// @return result The result as an uint256. function prbSqrt(uint256 x) pure returns (uint256 result) { if (x == 0) { return 0; } // For our first guess, we get 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; // Round down the result in case x is not a perfect square. uint256 roundedDownResult = x / result; if (result >= roundedDownResult) { result = roundedDownResult; } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; 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 amount that implies how many trailing decimals can be represented. SD1x18 constant UNIT = SD1x18.wrap(1e18); int256 constant uUNIT = 1e18;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import "./Casting.sol" as C; /// @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 { C.intoSD59x18, C.intoUD2x18, C.intoUD60x18, C.intoUint256, C.intoUint128, C.intoUint40, C.unwrap } for SD1x18 global;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; 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 Half the UNIT number. int256 constant uHALF_UNIT = 0.5e18; SD59x18 constant HALF_UNIT = SD59x18.wrap(uHALF_UNIT); /// @dev log2(10) as an SD59x18 number. int256 constant uLOG2_10 = 3_321928094887362347; SD59x18 constant LOG2_10 = SD59x18.wrap(uLOG2_10); /// @dev log2(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 amount that implies how many trailing decimals can be represented. int256 constant uUNIT = 1e18; SD59x18 constant UNIT = SD59x18.wrap(1e18); /// @dev Zero as an SD59x18 number. SD59x18 constant ZERO = SD59x18.wrap(0);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import "./Casting.sol" as C; import "./Helpers.sol" as H; import "./Math.sol" as M; /// @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 { C.intoInt256, C.intoSD1x18, C.intoUD2x18, C.intoUD60x18, C.intoUint256, C.intoUint128, C.intoUint40, C.unwrap } for SD59x18 global; /*////////////////////////////////////////////////////////////////////////// MATHEMATICAL FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ using { M.abs, M.avg, M.ceil, M.div, M.exp, M.exp2, M.floor, M.frac, M.gm, M.inv, M.log10, M.log2, M.ln, M.mul, M.pow, M.powu, M.sqrt } for SD59x18 global; /*////////////////////////////////////////////////////////////////////////// HELPER FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ using { H.add, H.and, H.eq, H.gt, H.gte, H.isZero, H.lshift, H.lt, H.lte, H.mod, H.neq, H.or, H.rshift, H.sub, H.uncheckedAdd, H.uncheckedSub, H.uncheckedUnary, H.xor } for SD59x18 global;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import { UD2x18 } from "./ValueType.sol"; /// @dev Euler's number as an UD2x18 number. UD2x18 constant E = UD2x18.wrap(2_718281828459045235); /// @dev The maximum value an UD2x18 number can have. uint64 constant uMAX_UD2x18 = 18_446744073709551615; UD2x18 constant MAX_UD2x18 = UD2x18.wrap(uMAX_UD2x18); /// @dev PI as an UD2x18 number. UD2x18 constant PI = UD2x18.wrap(3_141592653589793238); /// @dev The unit amount that implies how many trailing decimals can be represented. uint256 constant uUNIT = 1e18; UD2x18 constant UNIT = UD2x18.wrap(1e18);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import "./Casting.sol" as C; /// @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 { C.intoSD1x18, C.intoSD59x18, C.intoUD60x18, C.intoUint256, C.intoUint128, C.intoUint40, C.unwrap } for UD2x18 global;
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import { MAX_UINT40 } from "../Common.sol"; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { UD2x18 } from "../ud2x18/ValueType.sol"; import { UD60x18 } from "../ud60x18/ValueType.sol"; import { PRBMath_SD1x18_ToUD2x18_Underflow, PRBMath_SD1x18_ToUD60x18_Underflow, PRBMath_SD1x18_ToUint128_Underflow, PRBMath_SD1x18_ToUint256_Underflow, PRBMath_SD1x18_ToUint40_Overflow, PRBMath_SD1x18_ToUint40_Underflow } from "./Errors.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 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 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 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 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 PRBMath_SD1x18_ToUint40_Underflow(x); } if (xInt > int64(uint64(MAX_UINT40))) { revert PRBMath_SD1x18_ToUint40_Overflow(x); } result = uint40(uint64(xInt)); } /// @notice Alias for the `wrap` function. 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 the SD1x18 value type. function wrap(int64 x) pure returns (SD1x18 result) { result = SD1x18.wrap(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; 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 { PRBMath_SD59x18_IntoSD1x18_Overflow, PRBMath_SD59x18_IntoSD1x18_Underflow, PRBMath_SD59x18_IntoUD2x18_Overflow, PRBMath_SD59x18_IntoUD2x18_Underflow, PRBMath_SD59x18_IntoUD60x18_Underflow, PRBMath_SD59x18_IntoUint128_Overflow, PRBMath_SD59x18_IntoUint128_Underflow, PRBMath_SD59x18_IntoUint256_Underflow, PRBMath_SD59x18_IntoUint40_Overflow, PRBMath_SD59x18_IntoUint40_Underflow } from "./Errors.sol"; import { SD59x18 } from "./ValueType.sol"; /// @notice Casts an SD59x18 number into int256. /// @dev This is basically a functional alias for the `unwrap` function. 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 PRBMath_SD59x18_IntoSD1x18_Underflow(x); } if (xInt > uMAX_SD1x18) { revert 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 PRBMath_SD59x18_IntoUD2x18_Underflow(x); } if (xInt > int256(uint256(uMAX_UD2x18))) { revert 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 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 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 PRBMath_SD59x18_IntoUint128_Underflow(x); } if (xInt > int256(uint256(MAX_UINT128))) { revert 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 PRBMath_SD59x18_IntoUint40_Underflow(x); } if (xInt > int256(uint256(MAX_UINT40))) { revert PRBMath_SD59x18_IntoUint40_Overflow(x); } result = uint40(uint256(xInt)); } /// @notice Alias for the `wrap` function. function sd(int256 x) pure returns (SD59x18 result) { result = SD59x18.wrap(x); } /// @notice Alias for the `wrap` function. 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 the SD59x18 value type. function wrap(int256 x) pure returns (SD59x18 result) { result = SD59x18.wrap(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import { unwrap, 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(unwrap(x) + unwrap(y)); } /// @notice Implements the AND (&) bitwise operation in the SD59x18 type. function and(SD59x18 x, int256 bits) pure returns (SD59x18 result) { return wrap(unwrap(x) & bits); } /// @notice Implements the equal (=) operation in the SD59x18 type. function eq(SD59x18 x, SD59x18 y) pure returns (bool result) { result = unwrap(x) == unwrap(y); } /// @notice Implements the greater than operation (>) in the SD59x18 type. function gt(SD59x18 x, SD59x18 y) pure returns (bool result) { result = unwrap(x) > unwrap(y); } /// @notice Implements the greater than or equal to operation (>=) in the SD59x18 type. function gte(SD59x18 x, SD59x18 y) pure returns (bool result) { result = unwrap(x) >= unwrap(y); } /// @notice Implements a zero comparison check function in the SD59x18 type. function isZero(SD59x18 x) pure returns (bool result) { result = unwrap(x) == 0; } /// @notice Implements the left shift operation (<<) in the SD59x18 type. function lshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) { result = wrap(unwrap(x) << bits); } /// @notice Implements the lower than operation (<) in the SD59x18 type. function lt(SD59x18 x, SD59x18 y) pure returns (bool result) { result = unwrap(x) < unwrap(y); } /// @notice Implements the lower than or equal to operation (<=) in the SD59x18 type. function lte(SD59x18 x, SD59x18 y) pure returns (bool result) { result = unwrap(x) <= unwrap(y); } /// @notice Implements the unchecked modulo operation (%) in the SD59x18 type. function mod(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { result = wrap(unwrap(x) % unwrap(y)); } /// @notice Implements the not equal operation (!=) in the SD59x18 type. function neq(SD59x18 x, SD59x18 y) pure returns (bool result) { result = unwrap(x) != unwrap(y); } /// @notice Implements the OR (|) bitwise operation in the SD59x18 type. function or(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { result = wrap(unwrap(x) | unwrap(y)); } /// @notice Implements the right shift operation (>>) in the SD59x18 type. function rshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) { result = wrap(unwrap(x) >> bits); } /// @notice Implements the checked subtraction operation (-) in the SD59x18 type. function sub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { result = wrap(unwrap(x) - unwrap(y)); } /// @notice Implements the unchecked addition operation (+) in the SD59x18 type. function uncheckedAdd(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { unchecked { result = wrap(unwrap(x) + unwrap(y)); } } /// @notice Implements the unchecked subtraction operation (-) in the SD59x18 type. function uncheckedSub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { unchecked { result = wrap(unwrap(x) - unwrap(y)); } } /// @notice Implements the unchecked unary minus operation (-) in the SD59x18 type. function uncheckedUnary(SD59x18 x) pure returns (SD59x18 result) { unchecked { result = wrap(-unwrap(x)); } } /// @notice Implements the XOR (^) bitwise operation in the SD59x18 type. function xor(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { result = wrap(unwrap(x) ^ unwrap(y)); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import { MAX_UINT128, MAX_UINT40, msb, mulDiv, mulDiv18, prbExp2, prbSqrt } from "../Common.sol"; import { uHALF_UNIT, uLOG2_10, uLOG2_E, uMAX_SD59x18, uMAX_WHOLE_SD59x18, uMIN_SD59x18, uMIN_WHOLE_SD59x18, UNIT, uUNIT, ZERO } from "./Constants.sol"; import { PRBMath_SD59x18_Abs_MinSD59x18, PRBMath_SD59x18_Ceil_Overflow, PRBMath_SD59x18_Div_InputTooSmall, PRBMath_SD59x18_Div_Overflow, PRBMath_SD59x18_Exp_InputTooBig, PRBMath_SD59x18_Exp2_InputTooBig, PRBMath_SD59x18_Floor_Underflow, PRBMath_SD59x18_Gm_Overflow, PRBMath_SD59x18_Gm_NegativeProduct, PRBMath_SD59x18_Log_InputTooSmall, PRBMath_SD59x18_Mul_InputTooSmall, PRBMath_SD59x18_Mul_Overflow, PRBMath_SD59x18_Powu_Overflow, PRBMath_SD59x18_Sqrt_NegativeInput, PRBMath_SD59x18_Sqrt_Overflow } from "./Errors.sol"; import { unwrap, wrap } from "./Helpers.sol"; import { SD59x18 } from "./ValueType.sol"; /// @notice Calculate 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. function abs(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = unwrap(x); if (xInt == uMIN_SD59x18) { revert PRBMath_SD59x18_Abs_MinSD59x18(); } result = xInt < 0 ? wrap(-xInt) : x; } /// @notice Calculates the arithmetic average of x and y, rounding towards 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. function avg(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = unwrap(x); int256 yInt = unwrap(y); unchecked { // This is equivalent to "x / 2 + y / 2" but faster. // This operation can never overflow. int256 sum = (xInt >> 1) + (yInt >> 1); if (sum < 0) { // If at least one of x and y is odd, we add 1 to the result, since shifting negative numbers to the right rounds // down to infinity. The right part is equivalent to "sum + (x % 2 == 1 || y % 2 == 1)" but faster. assembly ("memory-safe") { result := add(sum, and(or(xInt, yInt), 1)) } } else { // We need to add 1 if both x and y are odd to account for the double 0.5 remainder that is truncated after shifting. result = wrap(sum + (xInt & yInt & 1)); } } } /// @notice Yields the smallest whole SD59x18 number greater 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 less than or equal to `MAX_WHOLE_SD59x18`. /// /// @param x The SD59x18 number to ceil. /// @param result The least number greater than or equal to x, as an SD59x18 number. function ceil(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = unwrap(x); if (xInt > uMAX_WHOLE_SD59x18) { revert 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. Rounds towards zero. /// /// @dev This is a variant of `mulDiv` that works with signed numbers. Works by computing the signs and the absolute values /// separately. /// /// Requirements: /// - All from `Common.mulDiv`. /// - None of the inputs can be `MIN_SD59x18`. /// - The denominator cannot be zero. /// - The result must fit within int256. /// /// Caveats: /// - All from `Common.mulDiv`. /// /// @param x The numerator as an SD59x18 number. /// @param y The denominator as an SD59x18 number. /// @param result The quotient as an SD59x18 number. function div(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = unwrap(x); int256 yInt = unwrap(y); if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) { revert 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 within int256. uint256 resultAbs = mulDiv(xAbs, uint256(uUNIT), yAbs); if (resultAbs > uint256(uMAX_SD59x18)) { revert PRBMath_SD59x18_Div_Overflow(x, y); } // Check if x and y have the same sign. This works thanks to two's complement; the left-most bit is the sign bit. bool sameSign = (xInt ^ yInt) > -1; // If the inputs don't have the same sign, the result should be negative. Otherwise, it should be positive. unchecked { result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs)); } } /// @notice Calculates the natural exponent of x. /// /// @dev Based on the formula: /// /// $$ /// e^x = 2^{x * log_2{e}} /// $$ /// /// Requirements: /// - All from `log2`. /// - x must be less than 133.084258667509499441. /// /// Caveats: /// - All from `exp2`. /// - For any x less than -41.446531673892822322, the result is zero. /// /// @param x The exponent as an SD59x18 number. /// @return result The result as an SD59x18 number. function exp(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = unwrap(x); // Without this check, the value passed to `exp2` would be less than -59.794705707972522261. if (xInt < -41_446531673892822322) { return ZERO; } // Without this check, the value passed to `exp2` would be greater than 192. if (xInt >= 133_084258667509499441) { revert PRBMath_SD59x18_Exp_InputTooBig(x); } unchecked { // Do the fixed-point multiplication inline 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. /// /// @dev Based on the formula: /// /// $$ /// 2^{-x} = \frac{1}{2^x} /// $$ /// /// See https://ethereum.stackexchange.com/q/79903/24693. /// /// Requirements: /// - x must be 192 or less. /// - The result must fit within `MAX_SD59x18`. /// /// Caveats: /// - For any x less than -59.794705707972522261, the result is zero. /// /// @param x The exponent as an SD59x18 number. /// @return result The result as an SD59x18 number. function exp2(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = unwrap(x); if (xInt < 0) { // 2^59.794705707972522262 is the maximum number whose inverse does not truncate down to zero. if (xInt < -59_794705707972522261) { return ZERO; } unchecked { // Do the fixed-point inversion $1/2^x$ inline to save gas. 1e36 is UNIT * UNIT. result = wrap(1e36 / unwrap(exp2(wrap(-xInt)))); } } else { // 2^192 doesn't fit within the 192.64-bit format used internally in this function. if (xInt >= 192e18) { revert 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 convert the result to int256 with no checks because the maximum input allowed in this function is 192. result = wrap(int256(prbExp2(x_192x64))); } } } /// @notice Yields the greatest whole SD59x18 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 integer less than or equal to x, as an SD59x18 number. function floor(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = unwrap(x); if (xInt < uMIN_WHOLE_SD59x18) { revert 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(unwrap(x) % uUNIT); } /// @notice Calculates the geometric mean of x and y, i.e. sqrt(x * y), rounding down. /// /// @dev Requirements: /// - x * y must fit within `MAX_SD59x18`, lest it overflows. /// - x * y must not be negative, since this library does not handle complex numbers. /// /// @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. function gm(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = unwrap(x); int256 yInt = unwrap(y); 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 PRBMath_SD59x18_Gm_Overflow(x, y); } // The product must not be negative, since this library does not handle complex numbers. if (xyInt < 0) { revert PRBMath_SD59x18_Gm_NegativeProduct(x, y); } // We don't need to multiply the result by `UNIT` here because the x*y product had picked up a factor of `UNIT` // during multiplication. See the comments within the `prbSqrt` function. uint256 resultUint = prbSqrt(uint256(xyInt)); result = wrap(int256(resultUint)); } } /// @notice Calculates 1 / x, rounding toward zero. /// /// @dev Requirements: /// - x cannot be zero. /// /// @param x The SD59x18 number for which to calculate the inverse. /// @return result The inverse as an SD59x18 number. function inv(SD59x18 x) pure returns (SD59x18 result) { // 1e36 is UNIT * UNIT. result = wrap(1e36 / unwrap(x)); } /// @notice Calculates the natural logarithm of x. /// /// @dev Based on the formula: /// /// $$ /// ln{x} = log_2{x} / log_2{e}$$. /// $$ /// /// Requirements: /// - All from `log2`. /// /// Caveats: /// - All from `log2`. /// - This doesn't return exactly 1 for 2.718281828459045235, for that more fine-grained precision is needed. /// /// @param x The SD59x18 number for which to calculate the natural logarithm. /// @return result The natural logarithm as an SD59x18 number. function ln(SD59x18 x) pure returns (SD59x18 result) { // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x) // can return is 195.205294292027477728. result = wrap((unwrap(log2(x)) * uUNIT) / uLOG2_E); } /// @notice Calculates the common logarithm of x. /// /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common /// logarithm based on the formula: /// /// $$ /// log_{10}{x} = log_2{x} / log_2{10} /// $$ /// /// Requirements: /// - All from `log2`. /// /// Caveats: /// - All from `log2`. /// /// @param x The SD59x18 number for which to calculate the common logarithm. /// @return result The common logarithm as an SD59x18 number. function log10(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = unwrap(x); if (xInt < 0) { revert PRBMath_SD59x18_Log_InputTooSmall(x); } // Note that the `mul` in this block is the assembly mul operation, not the 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 (unwrap(result) == uMAX_SD59x18) { unchecked { // Do the fixed-point division inline to save gas. result = wrap((unwrap(log2(x)) * uUNIT) / uLOG2_10); } } } /// @notice Calculates the binary logarithm of x. /// /// @dev Based on the iterative approximation algorithm. /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Requirements: /// - x must be greater than zero. /// /// Caveats: /// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation. /// /// @param x The SD59x18 number for which to calculate the binary logarithm. /// @return result The binary logarithm as an SD59x18 number. function log2(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = unwrap(x); if (xInt <= 0) { revert PRBMath_SD59x18_Log_InputTooSmall(x); } unchecked { // This works because of: // // $$ // log_2{x} = -log_2{\frac{1}{x}} // $$ int256 sign; if (xInt >= uUNIT) { sign = 1; } else { sign = -1; // Do the fixed-point inversion inline to save gas. The numerator is UNIT * UNIT. xInt = 1e36 / xInt; } // Calculate the integer part of the logarithm and add it to the result and finally calculate $y = x * 2^(-n)$. uint256 n = msb(uint256(xInt / uUNIT)); // This is the integer part of the logarithm as an SD59x18 number. The operation can't overflow // because n is maximum 255, UNIT is 1e18 and sign is either 1 or -1. int256 resultInt = int256(n) * uUNIT; // This is $y = x * 2^{-n}$. int256 y = xInt >> n; // If y is 1, 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 faster. int256 DOUBLE_UNIT = 2e18; for (int256 delta = uHALF_UNIT; delta > 0; delta >>= 1) { y = (y * y) / uUNIT; // Is $y^2 > 2$ and so in the range [2,4)? if (y >= DOUBLE_UNIT) { // Add the 2^{-m} factor to the logarithm. resultInt = resultInt + delta; // Corresponds to z/2 on Wikipedia. y >>= 1; } } resultInt *= sign; result = wrap(resultInt); } } /// @notice Multiplies two SD59x18 numbers together, returning a new SD59x18 number. /// /// @dev This is a variant of `mulDiv` that works with signed numbers and employs constant folding, i.e. the denominator /// is always 1e18. /// /// Requirements: /// - All from `Common.mulDiv18`. /// - None of the inputs can be `MIN_SD59x18`. /// - The result must fit within `MAX_SD59x18`. /// /// Caveats: /// - To understand how this works in detail, see the NatSpec comments in `Common.mulDivSigned`. /// /// @param x The multiplicand as an SD59x18 number. /// @param y The multiplier as an SD59x18 number. /// @return result The product as an SD59x18 number. function mul(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = unwrap(x); int256 yInt = unwrap(y); if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) { revert 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); } uint256 resultAbs = mulDiv18(xAbs, yAbs); if (resultAbs > uint256(uMAX_SD59x18)) { revert PRBMath_SD59x18_Mul_Overflow(x, y); } // Check if x and y have the same sign. This works thanks to two's complement; the left-most bit is the sign bit. bool sameSign = (xInt ^ yInt) > -1; // If the inputs have the same sign, the result should be negative. Otherwise, it should be positive. unchecked { result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs)); } } /// @notice Raises x to the power of y. /// /// @dev Based on the formula: /// /// $$ /// x^y = 2^{log_2{x} * y} /// $$ /// /// Requirements: /// - All from `exp2`, `log2` and `mul`. /// - x cannot be zero. /// /// Caveats: /// - All from `exp2`, `log2` and `mul`. /// - Assumes 0^0 is 1. /// /// @param x Number to raise to given power y, 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. function pow(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { int256 xInt = unwrap(x); int256 yInt = unwrap(y); if (xInt == 0) { result = yInt == 0 ? UNIT : ZERO; } else { if (yInt == uUNIT) { result = x; } else { result = exp2(mul(log2(x), y)); } } } /// @notice Raises x (an SD59x18 number) to the power y (unsigned basic integer) using the famous algorithm /// algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring /// /// Requirements: /// - All from `abs` and `Common.mulDiv18`. /// - The result must fit within `MAX_SD59x18`. /// /// Caveats: /// - All from `Common.mulDiv18`. /// - Assumes 0^0 is 1. /// /// @param x The base as an SD59x18 number. /// @param y The exponent as an uint256. /// @return result The result as an SD59x18 number. function powu(SD59x18 x, uint256 y) pure returns (SD59x18 result) { uint256 xAbs = uint256(unwrap(abs(x))); // 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)" but faster. uint256 yAux = y; for (yAux >>= 1; yAux > 0; yAux >>= 1) { xAbs = mulDiv18(xAbs, xAbs); // Equivalent to "y % 2 == 1" but faster. if (yAux & 1 > 0) { resultAbs = mulDiv18(resultAbs, xAbs); } } // The result must fit within `MAX_SD59x18`. if (resultAbs > uint256(uMAX_SD59x18)) { revert PRBMath_SD59x18_Powu_Overflow(x, y); } unchecked { // Is the base negative and the exponent an odd number? int256 resultInt = int256(resultAbs); bool isNegative = unwrap(x) < 0 && y & 1 == 1; if (isNegative) { resultInt = -resultInt; } result = wrap(resultInt); } } /// @notice Calculates the square root of x, rounding down. Only the positive root is returned. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Requirements: /// - x cannot be negative, since this library does not handle complex numbers. /// - x must be less than `MAX_SD59x18` divided by `UNIT`. /// /// @param x The SD59x18 number for which to calculate the square root. /// @return result The result as an SD59x18 number. function sqrt(SD59x18 x) pure returns (SD59x18 result) { int256 xInt = unwrap(x); if (xInt < 0) { revert PRBMath_SD59x18_Sqrt_NegativeInput(x); } if (xInt > uMAX_SD59x18 / uUNIT) { revert PRBMath_SD59x18_Sqrt_Overflow(x); } unchecked { // Multiply x by `UNIT` to account for the factor of `UNIT` that is picked up when multiplying two SD59x18 // numbers together (in this case, the two numbers are both the square root). uint256 resultUint = prbSqrt(uint256(xInt * uUNIT)); result = wrap(int256(resultUint)); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import { MAX_UINT40 } from "../Common.sol"; import { uMAX_SD1x18 } from "../sd1x18/Constants.sol"; import { SD1x18 } from "../sd1x18/ValueType.sol"; import { SD59x18 } from "../sd59x18/ValueType.sol"; import { UD2x18 } from "../ud2x18/ValueType.sol"; import { UD60x18 } from "../ud60x18/ValueType.sol"; import { PRBMath_UD2x18_IntoSD1x18_Overflow, PRBMath_UD2x18_IntoUint40_Overflow } from "./Errors.sol"; import { UD2x18 } from "./ValueType.sol"; /// @notice Casts an 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 PRBMath_UD2x18_IntoSD1x18_Overflow(x); } result = SD1x18.wrap(int64(xUint)); } /// @notice Casts an 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 an 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 an 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 an 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 an 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(MAX_UINT40)) { revert PRBMath_UD2x18_IntoUint40_Overflow(x); } result = uint40(xUint); } /// @notice Alias for the `wrap` function. function ud2x18(uint64 x) pure returns (UD2x18 result) { result = UD2x18.wrap(x); } /// @notice Unwrap an UD2x18 number into uint64. function unwrap(UD2x18 x) pure returns (uint64 result) { result = UD2x18.unwrap(x); } /// @notice Wraps an uint64 number into the UD2x18 value type. function wrap(uint64 x) pure returns (UD2x18 result) { result = UD2x18.wrap(x); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import { SD1x18 } from "./ValueType.sol"; /// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in UD2x18. error PRBMath_SD1x18_ToUD2x18_Underflow(SD1x18 x); /// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in UD60x18. error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x); /// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in uint128. error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x); /// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in uint256. error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x); /// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in uint40. error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x); /// @notice Emitted 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.13; import { SD59x18 } from "./ValueType.sol"; /// @notice Emitted when taking the absolute value of `MIN_SD59x18`. error PRBMath_SD59x18_Abs_MinSD59x18(); /// @notice Emitted when ceiling a number overflows SD59x18. error PRBMath_SD59x18_Ceil_Overflow(SD59x18 x); /// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18. error PRBMath_SD59x18_Convert_Overflow(int256 x); /// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18. error PRBMath_SD59x18_Convert_Underflow(int256 x); /// @notice Emitted when dividing two numbers and one of them is `MIN_SD59x18`. error PRBMath_SD59x18_Div_InputTooSmall(); /// @notice Emitted when dividing two numbers and one of the intermediary unsigned results overflows SD59x18. error PRBMath_SD59x18_Div_Overflow(SD59x18 x, SD59x18 y); /// @notice Emitted when taking the natural exponent of a base greater than 133.084258667509499441. error PRBMath_SD59x18_Exp_InputTooBig(SD59x18 x); /// @notice Emitted when taking the binary exponent of a base greater than 192. error PRBMath_SD59x18_Exp2_InputTooBig(SD59x18 x); /// @notice Emitted when flooring a number underflows SD59x18. error PRBMath_SD59x18_Floor_Underflow(SD59x18 x); /// @notice Emitted when taking the geometric mean of two numbers and their product is negative. error PRBMath_SD59x18_Gm_NegativeProduct(SD59x18 x, SD59x18 y); /// @notice Emitted when taking the geometric mean of two numbers and multiplying them overflows SD59x18. error PRBMath_SD59x18_Gm_Overflow(SD59x18 x, SD59x18 y); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in SD1x18. error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in SD1x18. error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in UD2x18. error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in UD2x18. error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in UD60x18. error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint128. error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint128. error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint256. error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint40. error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x); /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint40. error PRBMath_SD59x18_IntoUint40_Underflow(SD59x18 x); /// @notice Emitted when taking the logarithm of a number less than or equal to zero. error PRBMath_SD59x18_Log_InputTooSmall(SD59x18 x); /// @notice Emitted when multiplying two numbers and one of the inputs is `MIN_SD59x18`. error PRBMath_SD59x18_Mul_InputTooSmall(); /// @notice Emitted when multiplying two numbers and the intermediary absolute result overflows SD59x18. error PRBMath_SD59x18_Mul_Overflow(SD59x18 x, SD59x18 y); /// @notice Emitted when raising a number to a power and hte intermediary absolute result overflows SD59x18. error PRBMath_SD59x18_Powu_Overflow(SD59x18 x, uint256 y); /// @notice Emitted when taking the square root of a negative number. error PRBMath_SD59x18_Sqrt_NegativeInput(SD59x18 x); /// @notice Emitted when the calculating the square root overflows SD59x18. error PRBMath_SD59x18_Sqrt_Overflow(SD59x18 x);
// SPDX-License-Identifier: MIT pragma solidity >=0.8.13; import { UD2x18 } from "./ValueType.sol"; /// @notice Emitted when trying to cast a UD2x18 number that doesn't fit in SD1x18. error PRBMath_UD2x18_IntoSD1x18_Overflow(UD2x18 x); /// @notice Emitted 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/lib/prb-test/src/", "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/", "prb-test/=lib/prb-math/lib/prb-test/src/", "src/=lib/prb-math/src/" ], "optimizer": { "enabled": true, "runs": 200 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs" }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "london", "viaIR": false, "libraries": {} }
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"ExcessiveCollateralDecimals","type":"error"},{"inputs":[],"name":"ExcessiveFunding","type":"error"},{"inputs":[],"name":"FeesExceedReserves","type":"error"},{"inputs":[],"name":"InvalidBurnAmount","type":"error"},{"inputs":[],"name":"InvalidFee","type":"error"},{"inputs":[],"name":"InvalidFundingAmount","type":"error"},{"inputs":[],"name":"InvalidFundsLength","type":"error"},{"inputs":[],"name":"InvalidInvestmentAmount","type":"error"},{"inputs":[],"name":"InvalidOutcomeIndex","type":"error"},{"inputs":[],"name":"InvalidPrices","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":"OperationNotSupported","type":"error"},{"inputs":[],"name":"PoolValueZero","type":"error"},{"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"},{"inputs":[{"internalType":"uint256","name":"fee","type":"uint256"},{"components":[{"internalType":"contract IConditionalTokens","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":"marketParamsArray","type":"tuple[]"},{"internalType":"uint256[]","name":"addedFunds","type":"uint256[]"}],"name":"createAndFundMarketsWithPrices","outputs":[{"internalType":"contract MarketMaker[]","name":"","type":"address[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"fee","type":"uint256"},{"components":[{"internalType":"contract IConditionalTokens","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 IConditionalTokens","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":"createMarketConcrete","outputs":[{"internalType":"contract MarketMaker","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IConditionalTokens","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":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
60a060405234801561001057600080fd5b5060405161001d9061004b565b604051809103906000f080158015610039573d6000803e3d6000fd5b506001600160a01b0316608052610058565b615edb806112ea83390190565b6080516112696100816000396000818161054d0152818161059701526106ed01526112696000f3fe608060405234801561001057600080fd5b50600436106100575760003560e01c806301ffc9a71461005c5780636d6898ba146100845780638cb2e620146100a4578063aecc550a146100cf578063e0578fce146100e2575b600080fd5b61006f61006a366004610c3f565b6100f5565b60405190151581526020015b60405180910390f35b610097610092366004610def565b61012c565b60405161007b9190610ee1565b6100b76100b2366004610f2e565b610411565b6040516001600160a01b03909116815260200161007b565b6100b76100dd366004610f2e565b610428565b6100b76100f0366004610f86565b6106d9565b60006001600160e01b031982166357662a8560e11b148061012657506301ffc9a760e01b6001600160e01b03198316145b92915050565b60608251825114610150576040516314b8875560e21b815260040160405180910390fd5b6000835167ffffffffffffffff81111561016c5761016c610c81565b604051908082528060200260200182016040528015610195578160200160208202803683370190505b5090506101c733306101a686610712565b6101b660408a0160208b01610fc9565b6001600160a01b0316929190610760565b6000805b85518110156103d95760006101fa89898985815181106101ed576101ed610fe6565b6020026020010151610411565b90508084838151811061020f5761020f610fe6565b60200260200101906001600160a01b031690816001600160a01b0316815250506000816001600160a01b03166375172a8b6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561026f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102939190610ffc565b11156102c5578582815181106102ab576102ab610fe6565b6020026020010151836102be919061102b565b92506103c8565b60008683815181106102d9576102d9610fe6565b602002602001015111156103c857610328818784815181106102fd576102fd610fe6565b60200260200101518a60200160208101906103189190610fc9565b6001600160a01b031691906107d1565b806001600160a01b031663b518d9a43388858151811061034a5761034a610fe6565b60200260200101516040518363ffffffff1660e01b81526004016103839291906001600160a01b03929092168252602082015260400190565b6020604051808303816000875af11580156103a2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103c69190610ffc565b505b506103d28161103e565b90506101cb565b5080156104055761040533826103f560408a0160208b01610fc9565b6001600160a01b031691906108f0565b5090505b949350505050565b600061041e848484610428565b90505b9392505050565b6020810151516000908082036104515760405163104272fb60e11b815260040160405180910390fd5b60006104606020860186610fc9565b6001600160a01b031663d96ee75461047e60a0880160808901610fc9565b865160405160e084901b6001600160e01b03191681526001600160a01b0390921660048301526024820152604481018590526064016020604051808303816000875af11580156104d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104f69190610ffc565b905060006105048683610920565b905060006040518060a00160405280848152602001876060015181526020018981526020018760200151815260200187604001516001600160801b0316815250905060006105727f000000000000000000000000000000000000000000000000000000000000000084610953565b90506001600160a01b0381163b156105905794506104219350505050565b60006105bc7f0000000000000000000000000000000000000000000000000000000000000000856109ad565b9050816001600160a01b0316816001600160a01b0316146105df576105df611057565b816105f060408b0160208c01610fc9565b6001600160a01b031661060660208c018c610fc9565b85516020808801516040808a015181516001600160a01b03898116825294810195909552908401919091526060830152919091169033907f2d357fefe8d7e1012a0782310cc7c7c6670f306a0d1e035815e27c11a5ea8c879060800160405180910390a460405163c1d82ed560e01b81526001600160a01b0382169063c1d82ed590610698908d9088906004016110e7565b600060405180830381600087803b1580156106b257600080fd5b505af11580156106c6573d6000803e3d6000fd5b50929d9c50505050505050505050505050565b6000806106e68484610920565b90506104097f000000000000000000000000000000000000000000000000000000000000000082610953565b600080805b83518110156107595783818151811061073257610732610fe6565b602002602001015182610745919061102b565b9150806107518161103e565b915050610717565b5092915050565b6040516001600160a01b03808516602483015283166044820152606481018290526107cb9085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152610a4a565b50505050565b80158061084b5750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa158015610825573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108499190610ffc565b155b6108bb5760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b60648201526084015b60405180910390fd5b6040516001600160a01b0383166024820152604481018290526108eb90849063095ea7b360e01b90606401610794565b505050565b6040516001600160a01b0383166024820152604481018290526108eb90849063a9059cbb60e01b90606401610794565b60008282604051602001610935929190611183565b60405160208183030381529060405280519060200120905092915050565b6040513060388201526f5af43d82803e903d91602b57fd5bf3ff60248201526014810192909252733d602d80600a3d3981f3363d3d373d3d3d363d73825260588201526037600c8201206078820152605560439091012090565b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b1760205281603760096000f590506001600160a01b0381166101265760405162461bcd60e51b815260206004820152601760248201527f455243313136373a2063726561746532206661696c656400000000000000000060448201526064016108b2565b6000610a9f826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316610b1c9092919063ffffffff16565b8051909150156108eb5780806020019051810190610abd919061119e565b6108eb5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016108b2565b606061041e848460008585600080866001600160a01b03168587604051610b4391906111e4565b60006040518083038185875af1925050503d8060008114610b80576040519150601f19603f3d011682016040523d82523d6000602084013e610b85565b606091505b5091509150610b9687838387610ba1565b979650505050505050565b60608315610c10578251600003610c09576001600160a01b0385163b610c095760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016108b2565b5081610409565b6104098383815115610c255781518083602001fd5b8060405162461bcd60e51b81526004016108b29190611200565b600060208284031215610c5157600080fd5b81356001600160e01b03198116811461042157600080fd5b600060a08284031215610c7b57600080fd5b50919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610cc057610cc0610c81565b604052919050565b600067ffffffffffffffff821115610ce257610ce2610c81565b5060051b60200190565b600082601f830112610cfd57600080fd5b81356020610d12610d0d83610cc8565b610c97565b82815260059290921b84018101918181019086841115610d3157600080fd5b8286015b84811015610d4c5780358352918301918301610d35565b509695505050505050565b600060808284031215610d6957600080fd5b6040516080810167ffffffffffffffff8282108183111715610d8d57610d8d610c81565b81604052829350843583526020850135915080821115610dac57600080fd5b50610db985828601610cec565b60208301525060408301356001600160801b0381168114610dd957600080fd5b6040820152606092830135920191909152919050565b6000806000806101008587031215610e0657600080fd5b843593506020610e1887828801610c69565b935060c086013567ffffffffffffffff80821115610e3557600080fd5b818801915088601f830112610e4957600080fd5b8135610e57610d0d82610cc8565b81815260059190911b8301840190848101908b831115610e7657600080fd5b8585015b83811015610eae57803585811115610e925760008081fd5b610ea08e89838a0101610d57565b845250918601918601610e7a565b509650505060e0880135925080831115610ec757600080fd5b5050610ed587828801610cec565b91505092959194509250565b6020808252825182820181905260009190848201906040850190845b81811015610f225783516001600160a01b031683529284019291840191600101610efd565b50909695505050505050565b600080600060e08486031215610f4357600080fd5b83359250610f548560208601610c69565b915060c084013567ffffffffffffffff811115610f7057600080fd5b610f7c86828701610d57565b9150509250925092565b60008060c08385031215610f9957600080fd5b610fa38484610c69565b9460a0939093013593505050565b6001600160a01b0381168114610fc657600080fd5b50565b600060208284031215610fdb57600080fd5b813561042181610fb1565b634e487b7160e01b600052603260045260246000fd5b60006020828403121561100e57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b8082018082111561012657610126611015565b60006001820161105057611050611015565b5060010190565b634e487b7160e01b600052600160045260246000fd5b803561107881610fb1565b6001600160a01b03908116835260208201359061109482610fb1565b90811660208401526040820135906110ab82610fb1565b90811660408401526060820135906110c282610fb1565b90811660608401526080820135906110d982610fb1565b808216608085015250505050565b6110f1818461106d565b60c060a082015260006101608201835160c084015260208085015160e08501526040850151610100850152606085015160a0610120860152828151808552610180870191508383019450600092505b808310156111605784518252938301936001929092019190830190611140565b5060808701516001600160801b0381166101408801529350979650505050505050565b60c08101611191828561106d565b8260a08301529392505050565b6000602082840312156111b057600080fd5b8151801515811461042157600080fd5b60005b838110156111db5781810151838201526020016111c3565b50506000910152565b600082516111f68184602087016111c0565b9190910192915050565b602081526000825180602084015261121f8160408501602087016111c0565b601f01601f1916919091016040019291505056fea2646970667358221220ea06c800035cad1fe0b273a2b5a72847a5f9cf7be7d55f5446cc5934f95b776064736f6c6343000811003360806040523480156200001157600080fd5b506200001c62000022565b620000e4565b600054610100900460ff16156200008f5760405162461bcd60e51b815260206004820152602760248201527f496e697469616c697a61626c653a20636f6e747261637420697320696e697469604482015266616c697a696e6760c81b606482015260840160405180910390fd5b60005460ff9081161015620000e2576000805460ff191660ff9081179091556040519081527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b565b615de780620000f46000396000f3fe608060405234801561001057600080fd5b50600436106102d65760003560e01c80637e11b31f11610182578063bc197c81116100e9578063dd62ed3e116100a2578063eb175b7e1161007c578063eb175b7e1461069b578063ee66875a146106b0578063f23a6e61146106ba578063f55c79d0146106cd57600080fd5b8063dd62ed3e14610654578063e03031a614610667578063e1cedbf01461068857600080fd5b8063bc197c81146105d6578063c1d82ed514610602578063c7ff158414610615578063cc071c4f1461061d578063d2da404014610630578063d3c9727c1461064157600080fd5b80639f2a29441161013b5780639f2a294414610556578063a457c2d714610577578063a9059cbb1461058a578063b2016bd41461059d578063b518d9a4146105b0578063b78d05f7146105c357600080fd5b80637e11b31f146104fc5780638ab0c0b2146105105780638ac2c680146105185780639003adfe14610533578063939c5f7a1461053b57806395d89b411461054e57600080fd5b80633706c4da1161024157806352375bb1116101fa578063702fa158116101d4578063702fa158146104b057806370a08231146104b857806372441d54146104cb57806375172a8b146104f457600080fd5b806352375bb1146104695780635bd9e299146104715780635d5d46131461049d57600080fd5b80633706c4da146103dc57806339509351146103e45780633c3ad82e146103f757806340993b261461040c5780634343116a1461042e578063480fa82e1461044157600080fd5b806316dbd7761161029357806316dbd7761461038d57806318160ddd146103a05780631ba2f531146103a857806323b872dd146103b05780632ddc7de7146103c3578063313ce567146103cd57600080fd5b806301ffc9a7146102db57806306fdde0314610303578063095ea7b3146103185780630b1af86a1461032b578063164e68de14610340578063168e41eb14610361575b600080fd5b6102ee6102e9366004615103565b6106e0565b60405190151581526020015b60405180910390f35b61030b610777565b6040516102fa9190615151565b6102ee610326366004615199565b610809565b610333610821565b6040516102fa9190615200565b61035361034e366004615213565b6108aa565b6040519081526020016102fa565b61010854610375906001600160801b031681565b6040516001600160801b0390911681526020016102fa565b61035361039b366004615213565b610964565b609a54610353565b610353610a16565b6102ee6103be366004615230565b610a87565b6103536101035481565b604051601281526020016102fa565b60cf54610353565b6102ee6103f2366004615199565b610aab565b61040a6104053660046152bc565b610acd565b005b61041f61041a3660046152fd565b610b10565b6040516102fa93929190615329565b61035361043c366004615348565b610b30565b61045461044f3660046152bc565b610b4b565b604080519283526020830191909152016102fa565b610333610be6565b61010254610485906001600160a01b031681565b6040516001600160a01b0390911681526020016102fa565b6103536104ab36600461536a565b610cf9565b610333610d05565b6103536104c6366004615213565b610d5d565b6103536104d9366004615213565b6001600160a01b0316600090815260ce602052604090205490565b610353610d78565b61010554610375906001600160801b031681565b610353610e18565b6101055461037590600160801b90046001600160801b031681565b610353610e27565b61035361054936600461536a565b610e39565b61030b610e5b565b610569610564366004615199565b610e6a565b6040516102fa929190615383565b6102ee610585366004615199565b611140565b6102ee610598366004615199565b6111c0565b60ca54610485906001600160a01b031681565b6103536105be366004615199565b6111ce565b61040a6105d13660046153a5565b611208565b6105e96105e4366004615511565b611249565b6040516001600160e01b031990911681526020016102fa565b61040a6106103660046155d6565b6112aa565b6102ee611770565b61041f61062b366004615624565b6117f7565b6097546001600160a01b0316610485565b61035361064f3660046152fd565b611a79565b61035361066236600461565f565b611adb565b61067a61067536600461536a565b611b06565b6040516102fa929190615698565b61040a61069636600461536a565b611c82565b6106a3611ce1565b6040516102fa91906156b1565b6103536101045481565b6105e96106c8366004615716565b611e12565b61041f6106db366004615348565b611e53565b60006001600160e01b031982166319a298e760e01b148061071157506001600160e01b0319821663034b690160e61b145b8061072c57506001600160e01b03198216630e1cedbf60e41b145b8061074757506001600160e01b031982166306e253b560e11b145b8061076257506001600160e01b03198216635ee02cbf60e01b145b80610771575061077182611eb0565b92915050565b6060609b80546107869061577e565b80601f01602080910402602001604051908101604052809291908181526020018280546107b29061577e565b80156107ff5780601f106107d4576101008083540402835291602001916107ff565b820191906000526020600020905b8154815290600101906020018083116107e257829003601f168201915b5050505050905090565b600033610817818585611ee5565b5060019392505050565b6060600061082d611ce1565b8051602080830151610108546060850151610109805460408051828802810188019091528181529798506108a49794956001600160801b0390941694929383018282801561089a57602002820191906000526020600020905b815481526020019060010190808311610886575b5050505050612009565b91505090565b60006108b582610964565b9050801561095f576001600160a01b038216600090815260cc6020526040812080548392906108e59084906157c8565b909155505060cd546108f89082906157c8565b60cd5560ca54610912906001600160a01b031683836121ed565b816001600160a01b03167fc0819c13be868895eb93e40eaceb96de976442fa1d404e5c55f14bb65a8c489a8260405161094d91815260200190565b60405180910390a261095f8282612250565b919050565b600080610970609a5490565b61097984610d5d565b60cb5461098691906157db565b6109909190615808565b6001600160a01b038416600090815260cc60205260409020549091506109b78260016157c8565b10156109c5576109c561581c565b6001600160a01b038316600090815260cc60205260409020546109e99082906122de565b6001600160a01b038416600090815260cc6020526040902054909150610a0f9082615832565b9392505050565b6000610a82610a23610be6565b610109805480602002602001604051908101604052809291908181526020018280548015610a7057602002820191906000526020600020905b815481526020019060010190808311610a5c575b5050505050610a7d610d78565b6122f4565b905090565b600033610a95858285612313565b610aa085858561238d565b506001949350505050565b600033610817818585610abe8383611adb565b610ac891906157c8565b611ee5565b610106546001600160a01b0316336001600160a01b031614610b0257604051633c6c145d60e01b815260040160405180910390fd5b610b0c8282612543565b5050565b6000806060610b21338787876117f7565b92509250925093509350939050565b60006040516329a270f560e01b815260040160405180910390fd5b60008060005b83811015610bde576000858583818110610b6d57610b6d615845565b9050602002016020810190610b829190615213565b90506000610b8f82610d5d565b905080600003610ba0575050610bcc565b6000610bac8383610e6a565b9150610bba905081866157c8565b9450610bc682876157c8565b95505050505b80610bd68161585b565b915050610b51565b509250929050565b61010a546060906000906001600160401b03811115610c0757610c076153ce565b604051908082528060200260200182016040528015610c30578160200160208202803683370190505b50905060005b61010a54811015610c7e5730828281518110610c5457610c54615845565b6001600160a01b039092166020928302919091019091015280610c768161585b565b915050610c36565b50610102546040516313849cfd60e21b81526001600160a01b0390911690634e1273f490610cb490849061010a906004016158a9565b600060405180830381865afa158015610cd1573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526108a49190810190615909565b600061077133836111ce565b60606101098054806020026020016040519081016040528092919081815260200182805480156107ff57602002820191906000526020600020905b815481526020019060010190808311610d40575050505050905090565b6001600160a01b031660009081526098602052604090205490565b60ca546040516370a0823160e01b815230600482015260009182916001600160a01b03909116906370a0823190602401602060405180830381865afa158015610dc5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610de9919061598e565b90506000610df5610e27565b905080821015610e0757610e0761581c565b610e118183615832565b9250505090565b610e246012600a615a83565b81565b600060cd5460cb54610a829190615832565b61010a8181548110610e4a57600080fd5b600091825260209091200154905081565b6060609c80546107869061577e565b610102546101035460405163de61ece160e01b81526060926000926001600160a01b039091169163de61ece191610ea79160040190815260200190565b602060405180830381865afa158015610ec4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ee89190615a8f565b610f055760405163d1d695db60e01b815260040160405180910390fd5b610f0e8361261e565b92509050610f1c848461265d565b61010a546000816001600160401b03811115610f3a57610f3a6153ce565b604051908082528060200260200182016040528015610f63578160200160208202803683370190505b50905060005b82811015610fa15780828281518110610f8457610f84615845565b602090810291909101015280610f998161585b565b915050610f69565b508215610fbf5760ca54610fbf906001600160a01b031687856121ed565b6101025460ca546101035460405163c87e500960e01b81526001600160a01b039384169363c87e500993611000938c93929091169187908b90600401615ab1565b6020604051808303816000875af115801561101f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611043919061598e565b61104d90846157c8565b925060006110636097546001600160a01b031690565b9050806001600160a01b0316876001600160a01b0316036110e05760405163d77eb4c760e01b815260048101859052602481018790526001600160a01b0382169063d77eb4c790604401600060405180830381600087803b1580156110c757600080fd5b505af11580156110db573d6000803e3d6000fd5b505050505b60408051600081526020810191829052906001600160a01b038916907f96bd1544577eb6c104cdc0a1e4eda89c64f8875c006dfda5baaef1aa5628b4b99061112d90889085908c90615b02565b60405180910390a2505050509250929050565b6000338161114e8286611adb565b9050838110156111b35760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084015b60405180910390fd5b610aa08286868403611ee5565b60003361081781858561238d565b60006111d8611770565b156111f6576040516323fa277f60e21b815260040160405180910390fd5b610a0f8383611203610a16565b612702565b610106546001600160a01b0316336001600160a01b03161461123d57604051633c6c145d60e01b815260040160405180910390fd5b61124681612880565b50565b60006001600160a01b0386163014801561126a57506001600160a01b038516155b801561128a5750610102546001600160a01b0316336001600160a01b0316145b1561129d575063bc197c8160e01b6112a1565b5060005b95945050505050565b600054610100900460ff16158080156112ca5750600054600160ff909116105b806112e45750303b1580156112e4575060005460ff166001145b6113475760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016111aa565b6000805460ff19166001179055801561136a576000805461ff0019166101001790555b61138261137d6060850160408601615213565b61290a565b61139a6113956040850160208601615213565b61293a565b6113a2612992565b6113af6020840184615213565b61010280546001600160a01b0319166001600160a01b03929092169190911790558135610103556020820135610104556113e7611770565b15611405576040516323fa277f60e21b815260040160405180910390fd5b60ca546040805163313ce56760e01b815290516000926001600160a01b03169163313ce5679160048083019260209291908290030181865afa15801561144f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114739190615b2b565b60ff169050600061148582600a615a83565b90506001600160801b0381106114ae576040516347aad2ef60e11b815260040160405180910390fd5b808460400135106114d2576040516358d620b360e01b815260040160405180910390fd5b604084013515611531576114ea8160408601356129bb565b61010580546001600160801b03908116600160801b9382168402179182905560009261151f92604089013592919004166157db565b1161152c5761152c61581c565b611548565b61010580546001600160801b0316600160801b1790555b6001600160801b0361155c6012600a615a83565b111561156a5761156a61581c565b60128210156115bd5761157e826012615832565b61158990600a615a83565b6115979060408601356157db565b61010580546001600160801b0319166001600160801b039290921691909117905561160b565b60128211156115ea576115d1601283615832565b6115dc90600a615a83565b611597906040860135615808565b61010580546001600160801b03191660408601356001600160801b03161790555b61161b6080860160608701615213565b61010680546001600160a01b0319166001600160a01b039290921691909117905561164c60a0860160808701615213565b61010780546001600160a01b0319166001600160a01b039283161790556101025460ca5461010354604051635d5fcaa760e11b81529184166004830152602482015291169063babf954e90604401600060405180830381865afa1580156116b7573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526116df9190810190615909565b80516116f49161010a91602090910190615068565b5061170a6117056060860186615b4e565b612543565b61172261171d60a08601608087016153a5565b612880565b5050801561176b576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498906020015b60405180910390a15b505050565b60006101045442101580610a825750610102546101035460405163de61ece160e01b81526001600160a01b039092169163de61ece1916117b69160040190815260200190565b602060405180830381865afa1580156117d3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a829190615a8f565b6000806060611804611770565b15611822576040516323fa277f60e21b815260040160405180910390fd5b61010554600160801b90046001600160801b031686101561185657604051631bf1f55760e11b815260040160405180910390fd5b6118626012600a615a83565b61010554611879906001600160801b0316886157db565b6118839190615808565b915060006118918388615832565b905060006118b960405180606001604052806000815260200160008152602001600081525090565b6118c383896129f2565b929850955092509050868610156118ed5760405163592d015360e01b815260040160405180910390fd5b6118f681612bc2565b61190e3360ca546001600160a01b031690308c612cb5565b61191785612ced565b81156119265761192682612d56565b6101025461010a80546001600160a01b039092169163f242432a9130918e91908d90811061195657611956615845565b60009182526020822001546040516001600160e01b031960e087901b1681526001600160a01b0394851660048201529390921660248401526044830191909152606482018a905260a0608483015260a482015260c401600060405180830381600087803b1580156119c657600080fd5b505af11580156119da573d6000803e3d6000fd5b505050506119e781612dec565b604080518a81526020810187905290810187905288906001600160a01b038c16907f64cc4fe16c02ad83cc7cef979438c326a32c6984201d43cc67efb86ba07c7e8b9060600160405180910390a37fd16db9df479b59fe65c1ac1cf7b45b12b0b432fe457d316acdcbe22356ea495484604051611a649190615200565b60405180910390a15050509450945094915050565b6000611a83611770565b15611aa1576040516323fa277f60e21b815260040160405180910390fd5b83600003611ac257604051637f28d71160e01b815260040160405180910390fd5b6040516329a270f560e01b815260040160405180910390fd5b6001600160a01b03918216600090815260996020908152604080832093909416825291909152205490565b6000606033611b148461261e565b9093509150611b23818561265d565b60ca54611b3a906001600160a01b031682856121ed565b61010254604051631759616b60e11b81526001600160a01b0390911690632eb2c2d690611b73903090859061010a908890600401615b97565b600060405180830381600087803b158015611b8d57600080fd5b505af1158015611ba1573d6000803e3d6000fd5b505050506000611bb96097546001600160a01b031690565b9050806001600160a01b0316826001600160a01b031603611c365760405163d77eb4c760e01b815260048101859052602481018690526001600160a01b0382169063d77eb4c790604401600060405180830381600087803b158015611c1d57600080fd5b505af1158015611c31573d6000803e3d6000fd5b505050505b816001600160a01b03167f96bd1544577eb6c104cdc0a1e4eda89c64f8875c006dfda5baaef1aa5628b4b9858588604051611c7393929190615b02565b60405180910390a25050915091565b610107546001600160a01b0316336001600160a01b031614611cb757604051633c6c145d60e01b815260040160405180910390fd5b61010454811115611cdb57604051635ec5096760e11b815260040160405180910390fd5b61010455565b611d0c6040518060800160405280600081526020016000815260200160008152602001606081525090565b6000611d16610d78565b90506040518060800160405280611d2c60cf5490565b8152602001828152602001828152602001611d45610be6565b905291506000611d5d6097546001600160a01b031690565b90506001600160a01b03811615611e0d57604051639093708360e01b815230600482015260009081906001600160a01b038416906390937083906024016040805180830381865afa158015611db6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dda9190615bf2565b915091508085600001818151611df091906157c8565b905250602085018051839190611e079083906157c8565b90525050505b505090565b60006001600160a01b03861630148015611e405750610102546001600160a01b0316336001600160a01b0316145b1561129d575063f23a6e6160e01b6112a1565b6000806060611e646012600a615a83565b61010554611e7b906001600160801b0316876157db565b611e859190615808565b91506000611e938387615832565b9050611e9f81866129f2565b509198949750909550929350505050565b60006001600160e01b03198216630271189760e51b148061077157506301ffc9a760e01b6001600160e01b0319831614610771565b6001600160a01b038316611f475760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b60648201526084016111aa565b6001600160a01b038216611fa85760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b60648201526084016111aa565b6001600160a01b0383811660008181526099602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6060825182511461202d5760405163104272fb60e11b815260040160405180910390fd5b8560000361204e57604051636cdaa7bb60e01b815260040160405180910390fd5b81516001600160401b03811115612067576120676153ce565b604051908082528060200260200182016040528015612090578160200160208202803683370190505b50905060006120a16012600a615a83565b905060005b82518110156121e2576000878683815181106120c4576120c4615845565b60200260200101516120d691906157c8565b90506000805b8651811015612149578381146121375761212a8588838151811061210257612102615845565b602002602001015189878151811061211c5761211c615845565b60200260200101518c612f7c565b61213490836157c8565b91505b806121418161585b565b9150506120dc565b50600061216e87858151811061216157612161615845565b6020026020010151612f9f565b905061217c83838d84613125565b9150600061218a86846157c8565b9050806121996012600a615a83565b6121a390886157db565b6121ad9190615808565b8786815181106121bf576121bf615845565b6020026020010181815250505050505080806121da9061585b565b9150506120a6565b505095945050505050565b6040516001600160a01b03831660248201526044810182905261176b90849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526131bf565b60006122646097546001600160a01b031690565b9050806001600160a01b0316836001600160a01b03160361176b576040516303f036cb60e41b8152600481018390526001600160a01b03821690633f036cb090602401600060405180830381600087803b1580156122c157600080fd5b505af11580156122d5573d6000803e3d6000fd5b50505050505050565b60008183116122ed5781610a0f565b5090919050565b6000816123018585613291565b61230b91906157c8565b949350505050565b600061231f8484611adb565b90506000198114612387578181101561237a5760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e636500000060448201526064016111aa565b6123878484848403611ee5565b50505050565b6001600160a01b0383166123f15760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b60648201526084016111aa565b6001600160a01b0382166124535760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b60648201526084016111aa565b61245e838383613350565b6001600160a01b038316600090815260986020526040902054818110156124d65760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b60648201526084016111aa565b6001600160a01b0380851660008181526098602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906125369086815260200190565b60405180910390a3612387565b61010a5481146125665760405163104272fb60e11b815260040160405180910390fd5b610104544210612574575050565b60006125b28383808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506134cb92505050565b90506125c06012600a615a83565b81146125df5760405163104272fb60e11b815260040160405180910390fd5b6125ec61010984846150b3565b507f03a664f27e7b54c980680357aa22860435f0c3f94a762b432f5659b103f500946101096040516117629190615c16565b60006060600061262d609a5490565b9050612641848261263c610d78565b613519565b92506126558482612650610be6565b613557565b915050915091565b8060000361267e576040516302075cc160e41b815260040160405180910390fd5b60006126ac61268c84610d5d565b6001600160a01b038516600090815260ce60205260409020548490613638565b6001600160a01b038416600090815260ce60205260408120805492935083929091906126d9908490615832565b925050819055508060cf60008282546126f29190615832565b9091555061176b90508383613685565b60008260000361272557604051632ec86ff560e21b815260040160405180910390fd5b61273883612732609a5490565b846137c5565b6001600160a01b038516600090815260ce6020526040812054919250906127609085906157c8565b90506001600160801b0381111561278a57604051637756904960e01b815260040160405180910390fd5b6001600160a01b038516600090815260ce6020526040812082905560cf80548692906127b79084906157c8565b909155505060ca5433906127d6906001600160a01b0316823088612cb5565b6000836127e288610d5d565b6127ec91906157c8565b90506001600160801b0381111561281657604051637756904960e01b815260040160405180910390fd5b6128208785613811565b866001600160a01b0316826001600160a01b03167fdcde3dce73cebc28787eaab2e2b0474ab6f06f519882e7ee490a3f57e46abed3888760405161286e929190918252602082015260400190565b60405180910390a35050509392505050565b61288c6012600a615a83565b816001600160801b0316106128b45760405163104272fb60e11b815260040160405180910390fd5b61010880546001600160801b0319166001600160801b0383169081179091556040519081527fe6fd5ad17f191cf089c4b3cf520ffadaad263225625ab1ef323eb95b0bf35fb5906020015b60405180910390a150565b600054610100900460ff166129315760405162461bcd60e51b81526004016111aa90615c29565b611246816138de565b600054610100900460ff166129615760405162461bcd60e51b81526004016111aa90615c29565b6129896040518060200160405280600081525060405180602001604052806000815250613a15565b61124681613a46565b600054610100900460ff166129b95760405162461bcd60e51b81526004016111aa90615c29565b565b600082156129e957816129cf600185615832565b6129d99190615808565b6129e49060016157c8565b610a0f565b50600092915050565b6000806060612a1b60405180606001604052806000815260200160008152602001600081525090565b6000612a25611ce1565b9050600080612ab589898560000151866020015161010860009054906101000a90046001600160801b03166001600160801b03168860600151610109805480602002602001604051908101604052809291908181526020018280548015612aab57602002820191906000526020600020905b815481526020019060010190808311612a97575b5050505050613b15565b604080516060810182528c81526020810184905290810182905291935091506000612ae86097546001600160a01b031690565b905060006040518060400160405280612b0084610d5d565b8152602001612b0e609a5490565b90529050612b1e8b878584613d5c565b809950819b50829c50505050612bb18660000151876020015161010860009054906101000a90046001600160801b03166001600160801b0316896060015161010980548060200260200160405190810160405280929190818152602001828054801561089a5760200282019190600052602060002090815481526020019060010190808311610886575050505050612009565b975050505050505092959194509250565b6000612bd66097546001600160a01b031690565b825190915015610b0c57602082015115612bf257612bf261581c565b604082015115612c0457612c0461581c565b6001600160a01b038116612c1a57612c1a61581c565b8151604051635cd9ef8160e01b81526000916001600160a01b03841691635cd9ef8191612c4d9160040190815260200190565b60408051808303816000875af1158015612c6b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c8f9190615bf2565b50835190915081101561176b5760405163980427cb60e01b815260040160405180910390fd5b6040516001600160a01b03808516602483015283166044820152606481018290526123879085906323b872dd60e01b90608401612219565b612cf5610d78565b811115612d15576040516311d681c960e21b815260040160405180910390fd5b8060cb54612d2391906157c8565b60cb556040518181527f7545428d48c07276e600a1b3c9689be2420624a568454764744bed2ed4785b5e906020016128ff565b6101025460ca54612d74916001600160a01b03918216911683613f82565b6101025460ca5461010354604051636e8a12b160e11b81526001600160a01b03928316600482015260248101919091526044810184905291169063dd14256290606401600060405180830381600087803b158015612dd157600080fd5b505af1158015612de5573d6000803e3d6000fd5b5050505050565b6000612e006097546001600160a01b031690565b9050600082604001511180612e19575060008260200151115b15610b0c57815115612e2d57612e2d61581c565b6001600160a01b038116612e4357612e4361581c565b604082015115612e5b57612e5b81836040015161265d565b602082015115612e8457602082015160ca54612e84916001600160a01b039091169083906121ed565b6020820151604080840151905163d77eb4c760e01b81526001600160a01b0384169263d77eb4c792612ec192600401918252602082015260400190565b600060405180830381600087803b158015612edb57600080fd5b505af1158015612eef573d6000803e3d6000fd5b5060009250829150612efe9050565b604051908082528060200260200182016040528015612f27578160200160208202803683370190505b509050816001600160a01b03167f96bd1544577eb6c104cdc0a1e4eda89c64f8875c006dfda5baaef1aa5628b4b98460200151838660400151604051612f6f93929190615b02565b60405180910390a2505050565b6000612f8883836122de565b925082612f9585876157db565b6112a19190615808565b6040805161014081018252671bc16d674ec800008152671987adbcfc26e000602082015267177a3b78c9df20009181019190915267156217a05ad140006060820152671318fef1a6c220006080820152671088195fa3c9e00060a0820152670d9941201660e00060c0820152670a32144aa26d000060e082015267062ff6932687600061010082015267016345785d8a00006101208201526000908166b1a2bc2ec5000061305685826706f05b59d3b20000614097565b6130609190615832565b9050600061307566b1a2bc2ec5000083615808565b9050600061308a66b1a2bc2ec5000084615c74565b905060006130a3600961309e8560016157c8565b6140bb565b905066b1a2bc2ec500008582600a81106130bf576130bf615845565b60200201518685600a81106130d6576130d6615845565b60200201516130e59190615832565b6130ef90846157db565b6130f99190615808565b8584600a811061310b5761310b615845565b602002015161311a9190615832565b979650505050505050565b6000828510156131b657600061313b86846157db565b61314585856157db565b6131516012600a615a83565b61315b90896157db565b61316591906157c8565b61316f9190615832565b9050600061319261318087896157db565b8361318d6012600a615a83565b6140ca565b905060006131a086806157db565b90506131ac8183615808565b935050505061230b565b50919392505050565b6000613214826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166141799092919063ffffffff16565b80519091501561176b57808060200190518101906132329190615a8f565b61176b5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016111aa565b600082518251146132b55760405163104272fb60e11b815260040160405180910390fd5b60008060005b8451811015613345578581815181106132d6576132d6615845565b60200260200101518582815181106132f0576132f0615845565b602002602001015161330291906157db565b61330c90846157c8565b925084818151811061332057613320615845565b60200260200101518261333391906157c8565b915061333e8161585b565b90506132bb565b506112a182826129bb565b6001600160a01b0383161561336a57613368836108aa565b505b6000613375609a5490565b905060006001600160a01b038516156134155761339185610d5d565b6001600160a01b038616600090815260cc60205260409020546133b59085906157db565b6133bf9190615808565b6001600160a01b038616600090815260cc60205260409020549091506133e6908290615832565b6001600160a01b038616600090815260cc602052604090205560cd5461340d908290615832565b60cd55613451565b811561343957818360cb5461342a91906157db565b6134349190615808565b61343d565b60cb545b90508060cb5461344d91906157c8565b60cb555b6001600160a01b038416156134b3576001600160a01b038416600090815260cc60205260409020546134849082906157c8565b6001600160a01b038516600090815260cc602052604090205560cd546134ab9082906157c8565b60cd55612de5565b8060cb546134c19190615832565b60cb555050505050565b600080805b8351811015613512578381815181106134eb576134eb615845565b6020026020010151826134fe91906157c8565b91508061350a8161585b565b9150506134d0565b5092915050565b60008284111561353c576040516302075cc160e41b815260040160405180910390fd5b8315610a0f578261354d85846157db565b61230b9190615808565b60608284111561357a576040516302075cc160e41b815260040160405180910390fd5b81516001600160401b03811115613593576135936153ce565b6040519080825280602002602001820160405280156135bc578160200160208202803683370190505b5090508315610a0f5760005b82518110156136305783858483815181106135e5576135e5615845565b60200260200101516135f791906157db565b6136019190615808565b82828151811061361357613613615845565b6020908102919091010152806136288161585b565b9150506135c8565b509392505050565b60008383111561365b576040516302075cc160e41b815260040160405180910390fd5b831561367b578361366c84846157db565b6136769190615808565b61230b565b6000949350505050565b6001600160a01b0382166136e55760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b60648201526084016111aa565b6136f182600083613350565b6001600160a01b038216600090815260986020526040902054818110156137655760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b60648201526084016111aa565b6001600160a01b03831660008181526098602090815260408083208686039055609a80548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b6000816137d18161585b565b92506137e190506004600a615a83565b6137eb90846157c8565b9250600083116137fd576137fd61581c565b61230b8261380b85876157db565b906129bb565b6001600160a01b0382166138675760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f20616464726573730060448201526064016111aa565b61387360008383613350565b80609a600082825461388591906157c8565b90915550506001600160a01b0382166000818152609860209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b600054610100900460ff166139055760405162461bcd60e51b81526004016111aa90615c29565b6097546001600160a01b03161561391e5761391e61581c565b6001600160a01b038116158015906139a257506040516301ffc9a760e01b8152636831974d60e11b60048201526001600160a01b038216906301ffc9a790602401602060405180830381865afa15801561397c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139a09190615a8f565b155b156139cb576040516320d6c2ad60e01b81526001600160a01b03821660048201526024016111aa565b609780546001600160a01b0319166001600160a01b0383169081179091556040517f18da49b0178612731ce8a0d4a3052637cc23b8bfb85385e67c4373011d86ed1390600090a250565b600054610100900460ff16613a3c5760405162461bcd60e51b81526004016111aa90615c29565b610b0c8282614188565b600054610100900460ff16613a6d5760405162461bcd60e51b81526004016111aa90615c29565b6012816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613aad573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ad19190615b2b565b60ff161115613af3576040516347aad2ef60e11b815260040160405180910390fd5b60ca80546001600160a01b0319166001600160a01b0392909216919091179055565b60008083518810613b395760405163bdc9571560e01b815260040160405180910390fd5b8351835114613b5b5760405163104272fb60e11b815260040160405180910390fd5b86600003613b7c57604051636cdaa7bb60e01b815260040160405180910390fd5b60008060005b8551811015613c5c57808b14613c4a576000613ba06012600a615a83565b613baa908e6157db565b9050613bdc81888481518110613bc257613bc2615845565b6020026020010151898f8151811061211c5761211c615845565b613be690856157c8565b9350868281518110613bfa57613bfa615845565b60200260200101518d8b8a8581518110613c1657613c16615845565b6020026020010151613c2891906157c8565b613c3291906157c8565b613c3c91906157db565b613c4690846157c8565b9250505b80613c548161585b565b915050613b82565b506000613c74868c8151811061216157612161615845565b9050613cbb89888d81518110613c8c57613c8c615845565b6020026020010151613c9e91906157c8565b613caa6012600a615a83565b613cb49086615808565b8c846141c8565b9250613cc96012600a615a83565b613cd39084615808565b9450858b81518110613ce757613ce7615845565b6020026020010151858a898e81518110613d0357613d03615845565b6020026020010151613d1591906157c8565b613d1f9190615832565b613d2991906157db565b613d3390836157c8565b9150613d4b613d446012600a615a83565b83906129bb565b935050505097509795505050505050565b600080613d8360405180606001604052806000815260200160008152602001600081525090565b506040805160608101825260008082526020808301829052928201528551918601519091613db0916157c8565b9250613de286606001518881518110613dcb57613dcb615845565b6020026020010151846144c590919063ffffffff16565b9150600085600001518760400151613dfa91906157c8565b9050808310613e1457808303825260006040880152613ecf565b6000613e2684830388600001516140bb565b90506000866020015111613e3c57613e3c61581c565b855115613eaf576000886020015189604001518960400151613e5e91906157c8565b613e689190615832565b6020880151885191925090613e7d90846157db565b613e879190615808565b60208086018290528801518291613e9e91906157db565b613ea89190615808565b6040850152505b6020830151613ebe8584615832565b613ec89190615832565b6040890152505b855160208801518491613ee1916157c8565b613eeb9190615832565b602088015260005b876060015151811015613f76578388606001518281518110613f1757613f17615845565b60200260200101818151613f2b91906157c8565b905250888103613f64578488606001518281518110613f4c57613f4c615845565b60200260200101818151613f609190615832565b9052505b80613f6e8161585b565b915050613ef3565b50509450945094915050565b801580613ffc5750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa158015613fd6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ffa919061598e565b155b6140675760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b60648201526084016111aa565b6040516001600160a01b03831660248201526044810182905261176b90849063095ea7b360e01b90606401612219565b60008284106140b3578184116140ad578361230b565b8161230b565b509092915050565b60008183106122ed5781610a0f565b6000808060001985870985870292508281108382030391505080600003614104578382816140fa576140fa6157f2565b0492505050610a0f565b80841161411057600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b606061230b84846000856144db565b600054610100900460ff166141af5760405162461bcd60e51b81526004016111aa90615c29565b609b6141bb8382615cd6565b50609c61176b8282615cd6565b60008060006141e5866141db878a6140bb565b61309e908a615832565b90506141f36012600a615a83565b6141fd90826157db565b92506142098188615832565b96506142158187615832565b91505080156144bc578560000361422c575061230b565b8386111561423c5761423c61581c565b67016345785d8a00008310156142545761425461581c565b671bc16d674ec8000083111561426c5761426c61581c565b6000614277876145ab565b9050600061428588866157db565b9050600061429382886145f2565b905060006142a185886157db565b905060006142af828a614601565b90506142c481680736ea4425c11ac630111590565b15614301576142d56012600a615a83565b6142e060018d615832565b6142ea91906157db565b6142f490886157c8565b965050505050505061230b565b60006143278561432161431a6143178e8e6157db565b90565b8990614610565b90614622565b9050600061433783620f42401190565b156143b257816143478186614634565b925061435d614356848e614601565b8290614610565b905061438b6143568d6143718160026157db565b61437b91906157db565b6143858689614634565b90614601565b9050600061439d896143218a85614610565b90506143a98782614643565b92505050614464565b6143c46143bf60506145ab565b841090565b1561440a5760006143d48461466a565b905060006143e28285614634565b905060006143f48a6143218b85614610565b90506144008882614643565b9350505050614464565b600061441d6144188561466a565b6146b7565b905060008e614433838661318d6012600a615a83565b61443c8a6146b7565b61444691906157c8565b6144509190615832565b905061445f614317828961380b565b925050505b61447581670de0b6b3a76400001190565b61447f5780614489565b670de0b6b3a76400005b90508087101561449b5761449b61581c565b6144a86143178883614622565b6144b2908a6157c8565b9850505050505050505b50949350505050565b60008183116144d5576000610a0f565b50900390565b60608247101561453c5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016111aa565b600080866001600160a01b031685876040516145589190615d95565b60006040518083038185875af1925050503d8060008114614595576040519150601f19603f3d011682016040523d82523d6000602084013e61459a565b606091505b509150915061311a878383876146cb565b60006145c1670de0b6b3a7640000600019615808565b8211156145e457604051631cd951a760e01b8152600481018390526024016111aa565b50670de0b6b3a76400000290565b6000610a0f61431783856157db565b6000610a0f6143178385615808565b6000610a0f82845b61431791906157c8565b6000610a0f82845b6143179190615832565b6000610a0f6143178484614744565b600082156129e9576129e46146638361465d8660016147f8565b90614804565b600161481c565b600081680736ea4425c11ac631811061469957604051630d7b1d6560e11b8152600481018490526024016111aa565b6714057b7ef767814f810261230b670de0b6b3a76400008204614828565b6000610771670de0b6b3a764000083615808565b6060831561473a578251600003614733576001600160a01b0385163b6147335760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016111aa565b508161230b565b61230b838361487d565b60008080600019848609848602925082811083820303915050670de0b6b3a7640000811061478f57604051635173648d60e01b815260048101869052602481018590526044016111aa565b6000670de0b6b3a76400008587099050816000036147bb575050670de0b6b3a764000090049050610771565b620400008184030492109003600160ee1b02177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac1066902905092915050565b6000610a0f828461462a565b6000610a0f61431784670de0b6b3a7640000856148a7565b6000610a0f8284614618565b600081680a688906bd8b00000081106148575760405163b3b6ba1f60e01b8152600481018490526024016111aa565b600061486f670de0b6b3a7640000604084901b615808565b905061230b61431782614908565b81511561488d5781518083602001fd5b8060405162461bcd60e51b81526004016111aa9190615151565b60008080600019858709858702925082811083820303915050806000036148d7578382816140fa576140fa6157f2565b83811061411057604051630c740aef60e31b81526004810187905260248101869052604481018590526064016111aa565b600160bf1b67ff00000000000000821615614a155767800000000000000082161561493c5768016a09e667f3bcc9090260401c5b67400000000000000082161561495b576801306fe0a31b7152df0260401c5b67200000000000000082161561497a576801172b83c7d517adce0260401c5b6710000000000000008216156149995768010b5586cf9890f62a0260401c5b6708000000000000008216156149b8576801059b0d31585743ae0260401c5b6704000000000000008216156149d757680102c9a3e778060ee70260401c5b6702000000000000008216156149f65768010163da9fb33356d80260401c5b670100000000000000821615614a1557680100b1afa5abcbed610260401c5b66ff000000000000821615614b14576680000000000000821615614a425768010058c86da1c09ea20260401c5b6640000000000000821615614a60576801002c605e2e8cec500260401c5b6620000000000000821615614a7e57680100162f3904051fa10260401c5b6610000000000000821615614a9c576801000b175effdc76ba0260401c5b6608000000000000821615614aba57680100058ba01fb9f96d0260401c5b6604000000000000821615614ad85768010002c5cc37da94920260401c5b6602000000000000821615614af6576801000162e525ee05470260401c5b6601000000000000821615614b145768010000b17255775c040260401c5b65ff0000000000821615614c0a5765800000000000821615614b3f576801000058b91b5bc9ae0260401c5b65400000000000821615614b5c57680100002c5c89d5ec6d0260401c5b65200000000000821615614b795768010000162e43f4f8310260401c5b65100000000000821615614b9657680100000b1721bcfc9a0260401c5b65080000000000821615614bb35768010000058b90cf1e6e0260401c5b65040000000000821615614bd0576801000002c5c863b73f0260401c5b65020000000000821615614bed57680100000162e430e5a20260401c5b65010000000000821615614c0a576801000000b1721835510260401c5b64ff00000000821615614cf757648000000000821615614c3357680100000058b90c0b490260401c5b644000000000821615614c4f5768010000002c5c8601cc0260401c5b642000000000821615614c6b576801000000162e42fff00260401c5b641000000000821615614c875768010000000b17217fbb0260401c5b640800000000821615614ca3576801000000058b90bfce0260401c5b640400000000821615614cbf57680100000002c5c85fe30260401c5b640200000000821615614cdb5768010000000162e42ff10260401c5b640100000000821615614cf757680100000000b17217f80260401c5b63ff000000821615614ddb576380000000821615614d1e5768010000000058b90bfc0260401c5b6340000000821615614d39576801000000002c5c85fe0260401c5b6320000000821615614d5457680100000000162e42ff0260401c5b6310000000821615614d6f576801000000000b17217f0260401c5b6308000000821615614d8a57680100000000058b90c00260401c5b6304000000821615614da55768010000000002c5c8600260401c5b6302000000821615614dc0576801000000000162e4300260401c5b6301000000821615614ddb5768010000000000b172180260401c5b62ff0000821615614eb65762800000821615614e00576801000000000058b90c0260401c5b62400000821615614e1a57680100000000002c5c860260401c5b62200000821615614e345768010000000000162e430260401c5b62100000821615614e4e57680100000000000b17210260401c5b62080000821615614e685768010000000000058b910260401c5b62040000821615614e82576801000000000002c5c80260401c5b62020000821615614e9c57680100000000000162e40260401c5b62010000821615614eb6576801000000000000b1720260401c5b61ff00821615614f8857618000821615614ed957680100000000000058b90260401c5b614000821615614ef25768010000000000002c5d0260401c5b612000821615614f0b576801000000000000162e0260401c5b611000821615614f245768010000000000000b170260401c5b610800821615614f3d576801000000000000058c0260401c5b610400821615614f5657680100000000000002c60260401c5b610200821615614f6f57680100000000000001630260401c5b610100821615614f8857680100000000000000b10260401c5b60ff821615615051576080821615614fa957680100000000000000590260401c5b6040821615614fc1576801000000000000002c0260401c5b6020821615614fd957680100000000000000160260401c5b6010821615614ff1576801000000000000000b0260401c5b600882161561500957680100000000000000060260401c5b600482161561502157680100000000000000030260401c5b600282161561503957680100000000000000010260401c5b600182161561505157680100000000000000010260401c5b670de0b6b3a76400000260409190911c60bf031c90565b8280548282559060005260206000209081019282156150a3579160200282015b828111156150a3578251825591602001919060010190615088565b506150af9291506150ee565b5090565b8280548282559060005260206000209081019282156150a3579160200282015b828111156150a35782358255916020019190600101906150d3565b5b808211156150af57600081556001016150ef565b60006020828403121561511557600080fd5b81356001600160e01b031981168114610a0f57600080fd5b60005b83811015615148578181015183820152602001615130565b50506000910152565b602081526000825180602084015261517081604085016020870161512d565b601f01601f19169190910160400192915050565b6001600160a01b038116811461124657600080fd5b600080604083850312156151ac57600080fd5b82356151b781615184565b946020939093013593505050565b600081518084526020808501945080840160005b838110156151f5578151875295820195908201906001016151d9565b509495945050505050565b602081526000610a0f60208301846151c5565b60006020828403121561522557600080fd5b8135610a0f81615184565b60008060006060848603121561524557600080fd5b833561525081615184565b9250602084013561526081615184565b929592945050506040919091013590565b60008083601f84011261528357600080fd5b5081356001600160401b0381111561529a57600080fd5b6020830191508360208260051b85010111156152b557600080fd5b9250929050565b600080602083850312156152cf57600080fd5b82356001600160401b038111156152e557600080fd5b6152f185828601615271565b90969095509350505050565b60008060006060848603121561531257600080fd5b505081359360208301359350604090920135919050565b8381528260208201526060604082015260006112a160608301846151c5565b6000806040838503121561535b57600080fd5b50508035926020909101359150565b60006020828403121561537c57600080fd5b5035919050565b60408152600061539660408301856151c5565b90508260208301529392505050565b6000602082840312156153b757600080fd5b81356001600160801b0381168114610a0f57600080fd5b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b038111828210171561540c5761540c6153ce565b604052919050565b60006001600160401b0382111561542d5761542d6153ce565b5060051b60200190565b600082601f83011261544857600080fd5b8135602061545d61545883615414565b6153e4565b82815260059290921b8401810191818101908684111561547c57600080fd5b8286015b848110156154975780358352918301918301615480565b509695505050505050565b600082601f8301126154b357600080fd5b81356001600160401b038111156154cc576154cc6153ce565b6154df601f8201601f19166020016153e4565b8181528460208386010111156154f457600080fd5b816020850160208301376000918101602001919091529392505050565b600080600080600060a0868803121561552957600080fd5b853561553481615184565b9450602086013561554481615184565b935060408601356001600160401b038082111561556057600080fd5b61556c89838a01615437565b9450606088013591508082111561558257600080fd5b61558e89838a01615437565b935060808801359150808211156155a457600080fd5b506155b1888289016154a2565b9150509295509295909350565b600060a082840312156155d057600080fd5b50919050565b60008060c083850312156155e957600080fd5b6155f384846155be565b915060a08301356001600160401b0381111561560e57600080fd5b61561a858286016155be565b9150509250929050565b6000806000806080858703121561563a57600080fd5b843561564581615184565b966020860135965060408601359560600135945092505050565b6000806040838503121561567257600080fd5b823561567d81615184565b9150602083013561568d81615184565b809150509250929050565b82815260406020820152600061230b60408301846151c5565b6000602080835260a0830184518285015281850151604085015260408501516060850152606085015160808086015281815180845260c0870191508483019350600092505b8083101561549757835182529284019260019290920191908401906156f6565b600080600080600060a0868803121561572e57600080fd5b853561573981615184565b9450602086013561574981615184565b9350604086013592506060860135915060808601356001600160401b0381111561577257600080fd5b6155b1888289016154a2565b600181811c9082168061579257607f821691505b6020821081036155d057634e487b7160e01b600052602260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b80820180821115610771576107716157b2565b8082028115828204841417610771576107716157b2565b634e487b7160e01b600052601260045260246000fd5b600082615817576158176157f2565b500490565b634e487b7160e01b600052600160045260246000fd5b81810381811115610771576107716157b2565b634e487b7160e01b600052603260045260246000fd5b60006001820161586d5761586d6157b2565b5060010190565b6000815480845260208085019450836000528060002060005b838110156151f55781548752958201956001918201910161588d565b604080825283519082018190526000906020906060840190828701845b828110156158eb5781516001600160a01b0316845292840192908401906001016158c6565b505050838103828501526158ff8186615874565b9695505050505050565b6000602080838503121561591c57600080fd5b82516001600160401b0381111561593257600080fd5b8301601f8101851361594357600080fd5b805161595161545882615414565b81815260059190911b8201830190838101908783111561597057600080fd5b928401925b8284101561311a57835182529284019290840190615975565b6000602082840312156159a057600080fd5b5051919050565b600181815b80851115610bde5781600019048211156159c8576159c86157b2565b808516156159d557918102915b93841c93908002906159ac565b6000826159f157506001610771565b816159fe57506000610771565b8160018114615a145760028114615a1e57615a3a565b6001915050610771565b60ff841115615a2f57615a2f6157b2565b50506001821b610771565b5060208310610133831016604e8410600b8410161715615a5d575081810a610771565b615a6783836159a7565b8060001904821115615a7b57615a7b6157b2565b029392505050565b6000610a0f83836159e2565b600060208284031215615aa157600080fd5b81518015158114610a0f57600080fd5b6001600160a01b038681168252851660208201526040810184905260a060608201819052600090615ae4908301856151c5565b8281036080840152615af681856151c5565b98975050505050505050565b838152606060208201526000615b1b60608301856151c5565b9050826040830152949350505050565b600060208284031215615b3d57600080fd5b815160ff81168114610a0f57600080fd5b6000808335601e19843603018112615b6557600080fd5b8301803591506001600160401b03821115615b7f57600080fd5b6020019150600581901b36038213156152b557600080fd5b6001600160a01b0385811682528416602082015260a060408201819052600090615bc390830185615874565b8281036060840152615bd581856151c5565b838103608090940193909352505060008152602001949350505050565b60008060408385031215615c0557600080fd5b505080516020909101519092909150565b602081526000610a0f6020830184615874565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b600082615c8357615c836157f2565b500690565b601f82111561176b57600081815260208120601f850160051c81016020861015615caf5750805b601f850160051c820191505b81811015615cce57828155600101615cbb565b505050505050565b81516001600160401b03811115615cef57615cef6153ce565b615d0381615cfd845461577e565b84615c88565b602080601f831160018114615d385760008415615d205750858301515b600019600386901b1c1916600185901b178555615cce565b600085815260208120601f198616915b82811015615d6757888601518255948401946001909101908401615d48565b5085821015615d855787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b60008251615da781846020870161512d565b919091019291505056fea2646970667358221220b56a92af957cf93b484d5db4b052181ae8489da85ec9a4e31186f942d994bccb64736f6c63430008110033
Deployed Bytecode
0x608060405234801561001057600080fd5b50600436106100575760003560e01c806301ffc9a71461005c5780636d6898ba146100845780638cb2e620146100a4578063aecc550a146100cf578063e0578fce146100e2575b600080fd5b61006f61006a366004610c3f565b6100f5565b60405190151581526020015b60405180910390f35b610097610092366004610def565b61012c565b60405161007b9190610ee1565b6100b76100b2366004610f2e565b610411565b6040516001600160a01b03909116815260200161007b565b6100b76100dd366004610f2e565b610428565b6100b76100f0366004610f86565b6106d9565b60006001600160e01b031982166357662a8560e11b148061012657506301ffc9a760e01b6001600160e01b03198316145b92915050565b60608251825114610150576040516314b8875560e21b815260040160405180910390fd5b6000835167ffffffffffffffff81111561016c5761016c610c81565b604051908082528060200260200182016040528015610195578160200160208202803683370190505b5090506101c733306101a686610712565b6101b660408a0160208b01610fc9565b6001600160a01b0316929190610760565b6000805b85518110156103d95760006101fa89898985815181106101ed576101ed610fe6565b6020026020010151610411565b90508084838151811061020f5761020f610fe6565b60200260200101906001600160a01b031690816001600160a01b0316815250506000816001600160a01b03166375172a8b6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561026f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102939190610ffc565b11156102c5578582815181106102ab576102ab610fe6565b6020026020010151836102be919061102b565b92506103c8565b60008683815181106102d9576102d9610fe6565b602002602001015111156103c857610328818784815181106102fd576102fd610fe6565b60200260200101518a60200160208101906103189190610fc9565b6001600160a01b031691906107d1565b806001600160a01b031663b518d9a43388858151811061034a5761034a610fe6565b60200260200101516040518363ffffffff1660e01b81526004016103839291906001600160a01b03929092168252602082015260400190565b6020604051808303816000875af11580156103a2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103c69190610ffc565b505b506103d28161103e565b90506101cb565b5080156104055761040533826103f560408a0160208b01610fc9565b6001600160a01b031691906108f0565b5090505b949350505050565b600061041e848484610428565b90505b9392505050565b6020810151516000908082036104515760405163104272fb60e11b815260040160405180910390fd5b60006104606020860186610fc9565b6001600160a01b031663d96ee75461047e60a0880160808901610fc9565b865160405160e084901b6001600160e01b03191681526001600160a01b0390921660048301526024820152604481018590526064016020604051808303816000875af11580156104d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104f69190610ffc565b905060006105048683610920565b905060006040518060a00160405280848152602001876060015181526020018981526020018760200151815260200187604001516001600160801b0316815250905060006105727f00000000000000000000000040fdaf9c9e085ec6208f10c152a81e62d989f7da84610953565b90506001600160a01b0381163b156105905794506104219350505050565b60006105bc7f00000000000000000000000040fdaf9c9e085ec6208f10c152a81e62d989f7da856109ad565b9050816001600160a01b0316816001600160a01b0316146105df576105df611057565b816105f060408b0160208c01610fc9565b6001600160a01b031661060660208c018c610fc9565b85516020808801516040808a015181516001600160a01b03898116825294810195909552908401919091526060830152919091169033907f2d357fefe8d7e1012a0782310cc7c7c6670f306a0d1e035815e27c11a5ea8c879060800160405180910390a460405163c1d82ed560e01b81526001600160a01b0382169063c1d82ed590610698908d9088906004016110e7565b600060405180830381600087803b1580156106b257600080fd5b505af11580156106c6573d6000803e3d6000fd5b50929d9c50505050505050505050505050565b6000806106e68484610920565b90506104097f00000000000000000000000040fdaf9c9e085ec6208f10c152a81e62d989f7da82610953565b600080805b83518110156107595783818151811061073257610732610fe6565b602002602001015182610745919061102b565b9150806107518161103e565b915050610717565b5092915050565b6040516001600160a01b03808516602483015283166044820152606481018290526107cb9085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152610a4a565b50505050565b80158061084b5750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa158015610825573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108499190610ffc565b155b6108bb5760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b60648201526084015b60405180910390fd5b6040516001600160a01b0383166024820152604481018290526108eb90849063095ea7b360e01b90606401610794565b505050565b6040516001600160a01b0383166024820152604481018290526108eb90849063a9059cbb60e01b90606401610794565b60008282604051602001610935929190611183565b60405160208183030381529060405280519060200120905092915050565b6040513060388201526f5af43d82803e903d91602b57fd5bf3ff60248201526014810192909252733d602d80600a3d3981f3363d3d373d3d3d363d73825260588201526037600c8201206078820152605560439091012090565b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b1760205281603760096000f590506001600160a01b0381166101265760405162461bcd60e51b815260206004820152601760248201527f455243313136373a2063726561746532206661696c656400000000000000000060448201526064016108b2565b6000610a9f826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316610b1c9092919063ffffffff16565b8051909150156108eb5780806020019051810190610abd919061119e565b6108eb5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016108b2565b606061041e848460008585600080866001600160a01b03168587604051610b4391906111e4565b60006040518083038185875af1925050503d8060008114610b80576040519150601f19603f3d011682016040523d82523d6000602084013e610b85565b606091505b5091509150610b9687838387610ba1565b979650505050505050565b60608315610c10578251600003610c09576001600160a01b0385163b610c095760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016108b2565b5081610409565b6104098383815115610c255781518083602001fd5b8060405162461bcd60e51b81526004016108b29190611200565b600060208284031215610c5157600080fd5b81356001600160e01b03198116811461042157600080fd5b600060a08284031215610c7b57600080fd5b50919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610cc057610cc0610c81565b604052919050565b600067ffffffffffffffff821115610ce257610ce2610c81565b5060051b60200190565b600082601f830112610cfd57600080fd5b81356020610d12610d0d83610cc8565b610c97565b82815260059290921b84018101918181019086841115610d3157600080fd5b8286015b84811015610d4c5780358352918301918301610d35565b509695505050505050565b600060808284031215610d6957600080fd5b6040516080810167ffffffffffffffff8282108183111715610d8d57610d8d610c81565b81604052829350843583526020850135915080821115610dac57600080fd5b50610db985828601610cec565b60208301525060408301356001600160801b0381168114610dd957600080fd5b6040820152606092830135920191909152919050565b6000806000806101008587031215610e0657600080fd5b843593506020610e1887828801610c69565b935060c086013567ffffffffffffffff80821115610e3557600080fd5b818801915088601f830112610e4957600080fd5b8135610e57610d0d82610cc8565b81815260059190911b8301840190848101908b831115610e7657600080fd5b8585015b83811015610eae57803585811115610e925760008081fd5b610ea08e89838a0101610d57565b845250918601918601610e7a565b509650505060e0880135925080831115610ec757600080fd5b5050610ed587828801610cec565b91505092959194509250565b6020808252825182820181905260009190848201906040850190845b81811015610f225783516001600160a01b031683529284019291840191600101610efd565b50909695505050505050565b600080600060e08486031215610f4357600080fd5b83359250610f548560208601610c69565b915060c084013567ffffffffffffffff811115610f7057600080fd5b610f7c86828701610d57565b9150509250925092565b60008060c08385031215610f9957600080fd5b610fa38484610c69565b9460a0939093013593505050565b6001600160a01b0381168114610fc657600080fd5b50565b600060208284031215610fdb57600080fd5b813561042181610fb1565b634e487b7160e01b600052603260045260246000fd5b60006020828403121561100e57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b8082018082111561012657610126611015565b60006001820161105057611050611015565b5060010190565b634e487b7160e01b600052600160045260246000fd5b803561107881610fb1565b6001600160a01b03908116835260208201359061109482610fb1565b90811660208401526040820135906110ab82610fb1565b90811660408401526060820135906110c282610fb1565b90811660608401526080820135906110d982610fb1565b808216608085015250505050565b6110f1818461106d565b60c060a082015260006101608201835160c084015260208085015160e08501526040850151610100850152606085015160a0610120860152828151808552610180870191508383019450600092505b808310156111605784518252938301936001929092019190830190611140565b5060808701516001600160801b0381166101408801529350979650505050505050565b60c08101611191828561106d565b8260a08301529392505050565b6000602082840312156111b057600080fd5b8151801515811461042157600080fd5b60005b838110156111db5781810151838201526020016111c3565b50506000910152565b600082516111f68184602087016111c0565b9190910192915050565b602081526000825180602084015261121f8160408501602087016111c0565b601f01601f1916919091016040019291505056fea2646970667358221220ea06c800035cad1fe0b273a2b5a72847a5f9cf7be7d55f5446cc5934f95b776064736f6c63430008110033
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.