Contract Name:
ConditionalTokens
Contract Source Code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import { ERC1155Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol";
import { IERC165Upgradeable } from "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { IConditionalTokens, IConditionalTokensV1_2, IConditionalTokensEventsV1_2 } from "./IConditionalTokensV1_2.sol";
import { ILegConditionalTokens } from "./ILegConditionalTokens.sol";
import { ConditionalTokensStorage, ConditionalTokensBase } from "./ConditionalTokensBase.sol";
import { ConditionID, QuestionID, PackedIndices, CTHelpers } from "./CTHelpers.sol";
import { PackedPrices } from "../PackedPrices.sol";
/// @dev Tokens that represent different outcomes of a condition.
/// Note ConditionalTokensStorage is last, so it's possible to upgrade if we
/// decide to inherit more contracts. They just have to come after the
/// ConditionalTokenStorage, in order for the upgrade to be compatible
contract ConditionalTokens is ConditionalTokensBase, IConditionalTokensV1_2, ILegConditionalTokens {
using Math for uint256;
uint256 public constant PARLAY_WIN_INDEX = 0;
uint256 public constant PARLAY_LOSS_INDEX = 1;
uint256 public constant PARLAY_REFUND_INDEX = 2;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
// solhint-disable-next-line no-empty-blocks
function _authorizeUpgrade(address) internal override onlyOwner { }
// solhint-disable-next-line ordering
function initialize() public initializer {
__ConditionalTokensBase_init();
}
/// @notice This function creates a new condition. If the condition is already created, this function is idempotent.
/// @dev The condition is stored by initializing the payoutNumerator for that particular condition.
/// Has to be idempotent. Initial prices are all 0, and the condition is unhalted
/// @param conditionOracle The account assigned to report the result for the
/// prepared condition, as well as adjust prices and halt time.
/// @param questionId An identifier for the question to be answered by the oracle.
/// @param outcomeSlotCount The number of outcome slots for this condition. Must not exceed 256.
/// @return The ConditionID for this condition
function prepareCondition(address conditionOracle, QuestionID questionId, uint256 outcomeSlotCount)
external
returns (ConditionID)
{
return _prepareCondition(conditionOracle, questionId, outcomeSlotCount);
}
/// @notice This function creates a new condition. If the condition is already created, this function is idempotent.
/// @dev Has to be called by the intended condition oracle, which allows this to also set the price and halt time
/// @param questionId An identifier for the question to be answered by the oracle.
/// @param outcomeSlotCount The number of outcome slots for this condition. Must not exceed 256.
/// @param packedPrices The initial fair prices for the condition in a PackedPrice encoding
/// @param haltTime_ The initial halt time for the condition
/// @return conditionId The ConditionID for this condition
function prepareConditionByOracle(
QuestionID questionId,
uint256 outcomeSlotCount,
bytes calldata packedPrices,
uint32 haltTime_
) external returns (ConditionID conditionId) {
address conditionOracle = _msgSender();
conditionId = _prepareCondition(conditionOracle, questionId, outcomeSlotCount);
ConditionalTokensStorage.PriceStorage storage priceStorage_ = priceStorage[conditionId];
// If prices/halt time first initialized by oracle, update
if (priceStorage_.packedPrices.length == 0) {
priceStorage[conditionId].haltTime = haltTime_;
priceStorage[conditionId].packedPrices = packedPrices;
emit HaltTimeUpdated(conditionId, haltTime_);
emit ConditionPricesUpdated(conditionId, packedPrices);
}
}
/// @notice Function used to report the result of a condition by the oracle
/// @dev Called by the oracle for reporting results of conditions. It sets the payout vector for a particular
/// question ID. The oracle must be the message sender for this transaction to succeed The payouts array should
/// have an equal length to outcomeSlotCount previously set when the condition was stored.
///
/// E.g:
/// 2 outcomes = [0,1] -> result: index 1
/// 3 outcomes = [1,0,0] -> result: index 0
/// 3 outcomes = [1,0,1] -> result: index 0 & 2
/// The values are not neccessary limited to 0 & 1.
/// @param questionId The question ID the oracle is answering for.
/// @param payouts results array provided by the oracle.
function reportPayouts(QuestionID questionId, uint256[] calldata payouts) public {
uint256 outcomeSlotCount = payouts.length;
uint256[] memory numerators = new uint256[](outcomeSlotCount);
uint256 den = 0;
for (uint256 i = 0; i < outcomeSlotCount; i++) {
uint256 num = payouts[i];
den = den + num;
numerators[i] = num;
}
// for parlays of max legs to work, payout denominator cannot be too large
if (den > PackedPrices.DIVISOR) revert InvalidPayoutArray();
_reportPayouts(_msgSender(), questionId, numerators, den);
}
/**
* @notice Report payout in batches for the conditions for the given
* `questionIDs` and their associated outcomes. The `payouts` array should
* contain the payout values for each outcome of each question. The
* `outcomeSlotCounts` array should have the number of outcomes for each
* question ID. Both arrays should be correctly ordered, with the payouts
* for each question's outcomes immediately following its corresponding
* question ID. For example:
*
* questionIDs = [question0 (2 outcomes), question1 (3 outcomes), question2 (2 outcomes)]
* payouts = [
* pay_0_0, pay_0_1, // payouts for question0, outcome0 and outcome1
* pay_1_0, pay_1_1, pay_1_2, // payouts for question1, outcome0, outcome1, and outcome2
* pay_2_0, pay_2_1 // payouts for question2, outcome0 and outcome1
* ]
* outcomeSlotCounts = [
* 2,
* 3,
* 2,
* ]
*
* @param questionIDs An array of QuestionIDs corresponding to the conditions to be resolved.
* @param payouts An array of payout values for each outcome of each question.
* @param outcomeSlotCounts An array containing the number of outcomes for each question ID.
*
*/
function batchReportPayouts(
QuestionID[] calldata questionIDs,
uint256[] calldata payouts,
uint256[] calldata outcomeSlotCounts
) external {
if (questionIDs.length != outcomeSlotCounts.length) revert InvalidOutcomeSlotCountsArray();
if (payouts.length < questionIDs.length) revert InvalidPayoutArray();
uint256 offset = 0;
for (uint256 i = 0; i < questionIDs.length; i++) {
uint256 outcomeSlotCount = outcomeSlotCounts[i];
reportPayouts(questionIDs[i], payouts[offset:offset + outcomeSlotCount]);
offset += outcomeSlotCount;
}
}
/// @inheritdoc IConditionalTokensV1_2
function updateFairPrices(ConditionID conditionId, bytes calldata packedPrices) public {
ConditionalTokensStorage.PriceStorage storage priceStorage_ = priceStorage[conditionId];
// Load both at the same time onto stack to save on `sload` instructions
address conditionOracle = priceStorage_.conditionOracle;
uint256 haltTime_ = priceStorage_.haltTime;
if (_msgSender() != conditionOracle) revert MustBeCalledByOracle();
// 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 oldLength = priceStorage_.packedPrices.length;
if (!(oldLength == 0 || packedPrices.length == oldLength)) revert InvalidPrices();
uint256 total = PackedPrices.sum(packedPrices);
if (total != PackedPrices.DIVISOR) revert InvalidPrices();
priceStorage_.packedPrices = packedPrices;
}
/// @inheritdoc IConditionalTokensV1_2
function batchUpdateFairPrices(PriceUpdate[] calldata priceUpdates) external {
for (uint256 i = 0; i < priceUpdates.length; ++i) {
updateFairPrices(priceUpdates[i].conditionId, priceUpdates[i].packedPrices);
}
}
/// @inheritdoc IConditionalTokensV1_2
function getFairPrices(ConditionID conditionId) public view returns (uint256[] memory fairPriceDecimals) {
fairPriceDecimals = PackedPrices.toPriceDecimals(priceStorage[conditionId].packedPrices);
}
/// @inheritdoc IConditionalTokensV1_2
function updateHaltTime(ConditionID conditionId, uint32 _haltTime) public {
ConditionalTokensStorage.PriceStorage storage priceStorage_ = priceStorage[conditionId];
address conditionOracle = priceStorage_.conditionOracle;
uint256 oldHaltTime = priceStorage_.haltTime;
if (_msgSender() != conditionOracle) revert MustBeCalledByOracle();
if (block.timestamp > oldHaltTime) revert InvalidHaltTime();
priceStorage[conditionId].haltTime = _haltTime;
emit HaltTimeUpdated(conditionId, _haltTime);
}
/// @inheritdoc IConditionalTokensV1_2
function batchUpdateHaltTimes(HaltUpdate[] calldata haltUpdates) external {
for (uint256 i = 0; i < haltUpdates.length; ++i) {
HaltUpdate calldata haltUpdate = haltUpdates[i];
updateHaltTime(haltUpdate.conditionId, haltUpdate.haltTime);
}
}
/// @inheritdoc IConditionalTokensV1_2
function haltTime(ConditionID conditionId) public view returns (uint32) {
return priceStorage[conditionId].haltTime;
}
/// @inheritdoc ILegConditionalTokens
function minHaltTime(ConditionID[] calldata conditionIds) external view returns (uint256 min) {
min = type(uint32).max;
for (uint256 i = 0; i < conditionIds.length; ++i) {
uint256 time = priceStorage[conditionIds[i]].haltTime;
if (time < min) {
min = time;
}
}
}
/// @inheritdoc IConditionalTokensV1_2
function isHalted(ConditionID conditionId) external view returns (bool) {
return isResolved(conditionId) || block.timestamp >= haltTime(conditionId);
}
function getPositionInfo(address account, IERC20 collateralToken, ConditionID conditionId)
external
view
returns (uint256[] memory balances, uint256[] memory fairPriceDecimals)
{
balances = balanceOfCondition(account, collateralToken, conditionId);
fairPriceDecimals = getFairPrices(conditionId);
}
function getPayouts(ConditionID conditionId)
external
view
returns (uint256[] memory numerators, uint256 denominator)
{
numerators = payoutNumerators[conditionId];
denominator = payoutDenominator[conditionId];
}
function getParlayFairPrices(ConditionID[] calldata conditionIds, PackedIndices indices)
external
view
returns (uint256[] memory fairPriceDecimals)
{
if (conditionIds.length == 0) revert ConditionNotFound();
uint256 winNumerator = 1;
uint256 denominator = 1;
for (uint256 i = 0; i < conditionIds.length; i++) {
ConditionID conditionId = conditionIds[i];
uint256 index = CTHelpers.getIndex(indices, i);
bytes memory packedPrices = priceStorage[conditionId].packedPrices;
winNumerator *= PackedPrices.valueAtIndex(packedPrices, index);
denominator *= PackedPrices.DIVISOR;
}
// If numerator ends up 0, then one of the prices was 0, which means the
// outcome index passed in was for a non-priced outcome (such as a
// refund), or condition doesn't exist
if (winNumerator == 0) revert InvalidIndex();
uint256 winPriceDecimal = winNumerator.mulDiv(PackedPrices.ONE_DECIMAL, denominator, Math.Rounding.Up);
fairPriceDecimals = new uint256[](2);
fairPriceDecimals[PARLAY_WIN_INDEX] = winPriceDecimal;
fairPriceDecimals[PARLAY_LOSS_INDEX] = PackedPrices.ONE_DECIMAL - winPriceDecimal;
}
function getParlayPayouts(ConditionID[] calldata conditionIds, PackedIndices indices)
external
view
returns (uint256[] memory numerators, uint256 denominator)
{
uint256 winNumerator = 1;
denominator = 1;
// Separate calculation if there's only a refund outcome
uint256 refundNumerator = 1;
uint256 refundDenominator = 1;
for (uint256 i = 0; i < conditionIds.length; i++) {
ConditionID conditionId = conditionIds[i];
// Parlay refunds are hard to handle, since they depend on the price
// of each leg _at the time of purchase_. This can be modeled in 3
// ways:
// - Have a separate outcome for every refund combination. This is a
// combinatorial explosion of possibilities, and not feasible.
// - Record prices of each leg at time of purchase. This has high
// storage costs, and necessitates changes to the interfaces between
// tokens and market makers. Not feasible.
// - An approximation of the refund based on _current_ prices of
// legs. If a leg of a parlay is pushed (has refund outcome), it is
// as if that leg didn't exist in the overall parlay, so the payout
// is multiplied by the current leg price.
//
// There is a special case if every leg is pushed and is refunded -
// in that case we can model it exactly in terms of a full refund of
// the parlay. We don't need to estimate it with the current prices
// of legs. You will see separate calculations of refundNumerator
// and refundDenominator for such a case.
//
// Now onto how to derive the calculation.
//
// If we don't consider refunds, the payout is simply all the leg
// outcome payout numerators multiplied (similar to deriving the
// parlay price from leg prices). Typically, payouts will be all or
// nothing, meaning numerator/denominator for legs will be 1/1 or
// 0/1. Multiplying a bunch of leg payouts together will either
// yield 1/1 or 0/1.
//
// This also generalizes if there is a some fractional payout
// between outcomes. If we model a push as a fractional payout
// across outcomes (which we no longer do), the same multiplying
// also works. E.g. 1/2 * 1/2 yields 1/4 of the total payout, since
// the payouts for the legs were each halved.
//
// Following this logic, if we assume prices stay constant for legs,
// then a partial refund of a parlay for pushed legs can be modeled
// as simply (payout * (product of prices of pushed legs))
//
// Finally the fully general case, if there are fractional payouts
// between regular and refund outcomes, then for each leg the
// numerator will be a blend between the full payout and refund
// payout, weighted by the outcome numerator.
// Regular leg outcome is multiplied by price of $1 (full payout)
// and refund outcome is multiplied by the leg outcome price (push
// of the leg)
//
// (leg outcome numerator * $1) + (refund outcome numerator * $outcome price)
uint256 legDenominator = payoutDenominator[conditionId];
assert(legDenominator <= PackedPrices.DIVISOR); // guaranteed during reportPayouts
// As said above, each final numerator is a blend of (price * leg
// numerator) values. Hence the denominator needs to be multiplied
// by price divisor as well
denominator *= (legDenominator * PackedPrices.DIVISOR);
{
uint256 index = CTHelpers.getIndex(indices, i);
uint256 legNumerator = payoutNumerators[conditionId][index];
uint256 legRefundOutcomeIndex = payoutNumerators[conditionId].length - 1;
uint256 legRefundNumerator = payoutNumerators[conditionId][legRefundOutcomeIndex];
bytes memory packedPrices = priceStorage[conditionId].packedPrices;
uint256 legPrice = PackedPrices.valueAtIndex(packedPrices, index);
// This is the blend between win outcome and refund at current price
uint256 blendedNumerator = legNumerator * PackedPrices.DIVISOR + legRefundNumerator * legPrice;
winNumerator *= blendedNumerator;
// We keep track of "pure refund" case separately.
refundNumerator *= legRefundNumerator;
refundDenominator *= legDenominator;
}
// Short circuit if any condition is already lost. Even if other
// conditions are not yet resolved, we can settle the parlay as lost
// if any one of the positions is lost
if (winNumerator == 0 && refundNumerator == 0 && legDenominator > 0) {
denominator = 1;
break;
}
}
// if any denominator is zero, then the final denominator is 0,
// indicating at least one condition hasn't yet settled
if (denominator == 0) revert ResultNotReceivedYet();
numerators = new uint256[](PARLAY_OUTCOME_SLOT_COUNT);
if (refundNumerator > 0 && refundNumerator == refundDenominator) {
// If every leg is a refund, we can do an exact refund,
// instead of modelling the refund in terms of current prices.
numerators[PARLAY_REFUND_INDEX] = refundNumerator;
denominator = refundDenominator;
} else {
// Otherwise there is some partial refund, in which case we use the
// current price estimation. This blends any refunds into the win outcome
numerators[PARLAY_WIN_INDEX] = winNumerator;
numerators[PARLAY_LOSS_INDEX] = denominator - winNumerator;
}
assert(denominator > 0);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC165Upgradeable, ERC1155Upgradeable)
returns (bool)
{
return interfaceId == type(IConditionalTokens).interfaceId
|| interfaceId == type(IConditionalTokensV1_2).interfaceId
|| interfaceId == type(ILegConditionalTokens).interfaceId || ERC1155Upgradeable.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155Upgradeable.sol";
import "./IERC1155ReceiverUpgradeable.sol";
import "./extensions/IERC1155MetadataURIUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable {
using AddressUpgradeable for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
function __ERC1155_init(string memory uri_) internal onlyInitializing {
__ERC1155_init_unchained(uri_);
}
function __ERC1155_init_unchained(string memory uri_) internal onlyInitializing {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC1155Upgradeable).interfaceId ||
interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: address zero is not a valid owner");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not token owner or approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not token owner or approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* 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 _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
_afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
_afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `ids` and `amounts` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
/**
* @dev Hook that is called after any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non-ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non-ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
/**
* @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[47] private __gap;
}
// 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.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 (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10**64) {
value /= 10**64;
result += 64;
}
if (value >= 10**32) {
value /= 10**32;
result += 32;
}
if (value >= 10**16) {
value /= 10**16;
result += 16;
}
if (value >= 10**8) {
value /= 10**8;
result += 8;
}
if (value >= 10**4) {
value /= 10**4;
result += 4;
}
if (value >= 10**2) {
value /= 10**2;
result += 2;
}
if (value >= 10**1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import { IConditionalTokensEvents, IConditionalTokens, IERC20, ConditionalTokensErrors } from "./IConditionalTokens.sol";
import { PackedPrices } from "../PackedPrices.sol";
import { ConditionID, QuestionID, CTHelpers } from "./CTHelpers.sol";
interface IConditionalTokensEventsV1_2 is IConditionalTokensEvents {
/// @dev Event emitted only when a condition is prepared to save on gas costs
/// @param conditionId which condition had its price set
/// @param packedPrices the encoded prices in a byte array
event ConditionPricesUpdated(ConditionID indexed conditionId, bytes packedPrices);
/// @dev Halt time for a condition has been updated
event HaltTimeUpdated(ConditionID indexed conditionId, uint32 haltTime);
}
interface IConditionalTokensV1_2 is IConditionalTokens, IConditionalTokensEventsV1_2 {
struct PriceUpdate {
ConditionID conditionId;
bytes packedPrices;
}
struct HaltUpdate {
ConditionID conditionId;
/// @dev haltTime as seconds since epoch, same as block.timestamp
/// unsigned 32bit epoch timestamp in seconds should be suitable until year 2106
uint32 haltTime;
}
function prepareConditionByOracle(
QuestionID questionId,
uint256 outcomeSlotCount,
bytes calldata packedPrices,
uint32 haltTime_
) external returns (ConditionID);
function updateFairPrices(ConditionID conditionId, bytes calldata packedPrices) external;
function batchUpdateFairPrices(PriceUpdate[] calldata priceUpdates) external;
function getFairPrices(ConditionID conditionId) external view returns (uint256[] memory fairPriceDecimals);
function updateHaltTime(ConditionID conditionId, uint32 haltTime) external;
function batchUpdateHaltTimes(HaltUpdate[] calldata haltUpdates) external;
/// @dev Returns the halt time of a condition. Will be 0 if no price oracle
/// is configured (if old prepareCondition was called).
function haltTime(ConditionID conditionId) external view returns (uint32);
/// @dev Returns if the condition is halted or already resolved. Halting
/// only effects price updates. If no price oracle was configured for a
/// condition, this will always return true. This is ok since it does not
/// affect any other aspect.
function isHalted(ConditionID conditionId) external view returns (bool);
/// @dev combines together balanceOfCondition and getFairPrices into one call to minimize gas usage
function getPositionInfo(address account, IERC20 collateralToken, ConditionID conditionId)
external
view
returns (uint256[] memory balances, uint256[] memory fairPriceDecimals);
/// @dev Get the current payouts for a condition.
function getPayouts(ConditionID conditionId)
external
view
returns (uint256[] memory numerators, uint256 denominator);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import { ConditionID, PackedIndices } from "./CTHelpers.sol";
interface ILegConditionalTokens {
/// @dev given conditions and indices within those conditions, gives the fair price for the parlay
function getParlayFairPrices(ConditionID[] calldata conditionIds, PackedIndices indices)
external
view
returns (uint256[] memory fairPriceDecimals);
/// @dev given conditions and indices within those conditions, gives the payout for the parlay
function getParlayPayouts(ConditionID[] calldata conditionIds, PackedIndices indices)
external
view
returns (uint256[] memory numerators, uint256 denominator);
/// @dev Get the minimum of all halt times of supplied conditions
/// @return min as uint256. This is more efficient to return in the evm
function minHaltTime(ConditionID[] calldata conditionIds) external view returns (uint256 min);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { UUPSUpgradeable } from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import { ERC1155Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IConditionalTokens } from "./IConditionalTokensV1_2.sol";
import { ConditionID, QuestionID, CollectionID, CTHelpers } from "./CTHelpers.sol";
import { ArrayMath } from "../Math.sol";
contract ConditionalTokensStorage {
struct PriceStorage {
/// @dev saving the condition oracle so it's cheaper to get the oracle
/// than recompute it using keccak every time from questionId
address conditionOracle; // offset 0, length 20 bytes
uint32 haltTime; // offset 20, length 4 bytes
// 8 bytes of padding available
bytes packedPrices; // offset 32
}
/// @dev payoutNumerators and payoutDenominator represent the payout vector associated a condition. PayoutNumberator
/// is initialized with a length equal to the outcomeSlotCount when the condition is prepared.
///
/// E.g:
/// condition with 3 outcomes [A, B, C], two of those are correct: A & B
/// payout vector = [0.5, 0.5, 0]
/// This is represented as:
/// payoutNumerators = [1,1,0] & payoutDenominator = 2
///
/// PayoutNumerators are also used as a check of initialization. If the numerators array is empty (has length zero),
/// the condition was not created/prepared.
///
/// PayoutDenominator is also used for checking if the condition has been resolved. If the denominator is non-zero,
/// then the condition has been resolved.
mapping(ConditionID => uint256[]) public payoutNumerators;
mapping(ConditionID => uint256) public payoutDenominator;
mapping(address => bool) public erc20Whitelist;
mapping(ConditionID => PriceStorage) public priceStorage;
// NOTE: for fee refunds.
// Potential fee solution - store `mapping(UserPositionID => UserPositionInfo)`, that has fee data.
// When doing a push, can refund the fees stored in UserPositionInfo, otherwise just ignore
// Will also need `mapping(TokenConditionID => uint256)` to store total fees gathered for condition + token
uint256[48] private __gap;
}
/// @dev Basic conditional tokens functionality
abstract contract ConditionalTokensBase is
UUPSUpgradeable,
IConditionalTokens,
ERC1155Upgradeable,
OwnableUpgradeable,
ConditionalTokensStorage
{
using SafeERC20 for IERC20;
using ArrayMath for uint256[];
/// @dev 3 outcomes, because last one is a refund
uint256 internal constant PARLAY_OUTCOME_SLOT_COUNT = 3;
// solhint-disable-next-line func-name-mixedcase
function __ConditionalTokensBase_init() internal onlyInitializing {
__ERC1155_init("");
__Ownable_init();
__UUPSUpgradeable_init();
__ConditionalTokensBase_init_unchained();
}
// solhint-disable-next-line func-name-mixedcase no-empty-blocks
function __ConditionalTokensBase_init_unchained() internal onlyInitializing { }
function setERC20Whitelist(IERC20 token, bool approved) external onlyOwner {
erc20Whitelist[address(token)] = approved;
}
function _prepareCondition(address conditionOracle, QuestionID questionId, uint256 outcomeSlotCount)
internal
returns (ConditionID)
{
// Limit of 256 because we use a partition array that is a number of 256 bits.
if (outcomeSlotCount < 2 || outcomeSlotCount > 255) revert InvalidOutcomeSlotsAmount();
ConditionID conditionId = CTHelpers.getConditionId(conditionOracle, questionId, outcomeSlotCount);
// If not prepared, initialize, and emit the event, otherwise just return existing conditionId
if (payoutNumerators[conditionId].length == 0) {
payoutNumerators[conditionId] = new uint256[](outcomeSlotCount);
priceStorage[conditionId].conditionOracle = conditionOracle;
// Start condition as unhalted. Otherwise not possible to change halt time
priceStorage[conditionId].haltTime = type(uint32).max;
emit ConditionPreparation(conditionId, conditionOracle, questionId, outcomeSlotCount);
}
return conditionId;
}
/// @dev Internal way for a Conditional Tokens contract to report payouts for a question.
/// @param numerators The numerators for the payout ratio for each outcome
/// @param denominator The sum of all the numerators
function _reportPayouts(address oracle, QuestionID questionId, uint256[] memory numerators, uint256 denominator)
internal
{
uint256 outcomeSlotCount = numerators.length;
if (outcomeSlotCount <= 1 || outcomeSlotCount > 255) revert InvalidOutcomeSlotsAmount();
ConditionID conditionId = CTHelpers.getConditionId(oracle, questionId, outcomeSlotCount);
if (payoutNumerators[conditionId].length != outcomeSlotCount) revert ConditionNotFound();
if (denominator == 0) revert PayoutsAreAllZero();
// If already reported, silently ignore to ease batch operations and idempotency
if (isResolved(conditionId)) return;
payoutNumerators[conditionId] = numerators;
payoutDenominator[conditionId] = denominator;
emit ConditionResolution(conditionId, oracle, questionId, outcomeSlotCount, numerators);
}
function isResolved(ConditionID conditionId) public view returns (bool) {
return payoutDenominator[conditionId] != 0;
}
/// @notice Deposits an amount of collateral (ERC20) into this contract and mints to the sender the same amount of
/// conditional tokens (ERC1155) for each of the outcomes in the specified condition ID.
/// @dev When splitting from the collateral, the function will attempt to transfer `amount` collateral from the
/// message sender to itself. Regardless, if successful, `amount` stake will be minted in the split target
/// positions. If any of the transfers, mints, or burns fail, the transaction will revert. The transaction will also
/// revert if the given partition is trivial, invalid, or refers to more slots than the condition is prepared with.
/// @param collateralToken The address of the positions' backing collateral token.
/// @param conditionId The ID of the condition to split on.
/// @param amount The amount of collateral or stake to split.
function splitPosition(IERC20 collateralToken, ConditionID conditionId, uint256 amount) external {
if (amount == 0) revert InvalidAmount();
// - Only validate erc20 whitelist here, as it's the only way to create conditional tokens.
// All other operations are only possible after splitting.
// - In the case where a token that was already whitelisted becomes
// blacklisted, we only prevent any further creation of conditional
// tokens, but allow existing positions to wind down to prevent trapping
// the collateral inside the ConditionalTokens contract
if (!erc20Whitelist[address(collateralToken)]) revert InvalidERC20();
uint256 outcomeSlotCount = payoutNumerators[conditionId].length;
if (outcomeSlotCount == 0) revert ConditionNotFound();
uint256[] memory positionIds = new uint256[](outcomeSlotCount);
uint256[] memory amounts = new uint256[](outcomeSlotCount);
for (uint256 i = 0; i < outcomeSlotCount; i++) {
positionIds[i] = CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(conditionId, i));
amounts[i] = amount;
}
collateralToken.safeTransferFrom(_msgSender(), address(this), amount);
_mintBatch(
_msgSender(),
// position ID is the ERC 1155 token ID
positionIds,
amounts,
""
);
emit PositionSplit(_msgSender(), collateralToken, conditionId, amount);
}
/// @notice Burns the specified amount of conditional tokens (ERC1155) for all the positions and returns to the
/// sender that amount of collateral (ERC20).
/// @param collateralToken The address of the positions' backing collateral token.
/// @param conditionId The ID of the condition to split on.
/// @param amount The quantity of conditional tokens to merge.
function mergePositions(IERC20 collateralToken, ConditionID conditionId, uint256 amount) external {
if (amount == 0) revert InvalidAmount();
uint256 outcomeSlotCount = payoutNumerators[conditionId].length;
if (outcomeSlotCount == 0) revert ConditionNotFound();
uint256[] memory positionIds = new uint256[](outcomeSlotCount);
uint256[] memory amounts = new uint256[](outcomeSlotCount);
for (uint256 i = 0; i < outcomeSlotCount; i++) {
positionIds[i] = CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(conditionId, i));
amounts[i] = amount;
}
_burnBatch(_msgSender(), positionIds, amounts);
collateralToken.safeTransfer(_msgSender(), amount);
emit PositionsMerge(_msgSender(), collateralToken, conditionId, amount);
}
/// @notice Redeems the collateral corresponding to a particular outcome of a condition
/// @param owner The owner account of the conditional tokens
/// @param conditionId The ID of the condition
/// @param index Outcome index to redeem
/// @param burnAmount Amount of conditional tokens to burn
/// @return totalPayout The amount of collateral that should be transferred back
function _redeemPosition(
address owner,
uint256 positionId,
ConditionID conditionId,
uint256 index,
uint256 burnAmount
) internal returns (uint256 totalPayout) {
uint256 denominator = payoutDenominator[conditionId];
if (denominator == 0) revert ResultNotReceivedYet();
uint256 outcomeSlotCount = payoutNumerators[conditionId].length;
assert(outcomeSlotCount != 0);
if (index >= outcomeSlotCount) revert InvalidIndex();
uint256 payoutNumerator = payoutNumerators[conditionId][index];
if (burnAmount > 0) {
totalPayout = (burnAmount * payoutNumerator) / denominator;
_burn(owner, positionId, burnAmount);
}
}
/// @notice Redeem conditional tokens into collateral based on their
/// reported payout value. Redeems the sender's tokens and gives the
/// proceeds to receiver.
/// @param receiver The address that will receive all the proceeds of the redemption.
/// @param collateralToken The address of the positions' backing collateral token.
/// @param conditionId The ID of the condition to split on.
/// @param indices Outcome indices to redeem.
/// @param quantities Quantity of conditional tokens for each index to be burned.
function redeemPositionsFor(
address receiver,
IERC20 collateralToken,
ConditionID conditionId,
uint256[] calldata indices,
uint256[] calldata quantities
) public returns (uint256 totalPayout) {
if (indices.length != quantities.length) revert InvalidQuantities();
address redeemer = _msgSender();
totalPayout = 0;
for (uint256 i = 0; i < indices.length; i++) {
uint256 positionId =
CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(conditionId, indices[i]));
totalPayout += _redeemPosition(redeemer, positionId, conditionId, indices[i], quantities[i]);
}
// Doing the emit here before the transfer to mirror the ordering done in redeemAll.
// There, all the PayoutRedemption emits are done one-by-one, follow by one large safeTransfer.
emit PayoutRedemptionFor(receiver, redeemer, collateralToken, conditionId, indices, quantities, totalPayout);
if (totalPayout > 0) {
collateralToken.safeTransfer(receiver, totalPayout);
}
}
/// @notice Redeem multiple conditions and outcomes in one call for the sender
/// @param collateralToken The address of the collateral token used to enter the positions
/// @param conditionIds an array of ConditionIDs to redeem
/// @param indices an array of outcome indices to redeem from the corresponding entry in the conditionIds array
function redeemAll(IERC20 collateralToken, ConditionID[] calldata conditionIds, uint256[] calldata indices)
external
{
redeemAllOf(_msgSender(), collateralToken, conditionIds, indices);
}
/// @notice Redeem multiple conditions and outcomes in one call on behalf of an owner
/// @param ownerAndReceiver The account of the owner of conditional tokens
/// @param collateralToken The address of the collateral token used to enter the positions
/// @param conditionIds an array of ConditionIDs to redeem
/// @param indices an array of outcome indices to redeem from the corresponding entry in the conditionIds array
function redeemAllOf(
address ownerAndReceiver,
IERC20 collateralToken,
ConditionID[] calldata conditionIds,
uint256[] calldata indices
) public returns (uint256 totalPayout) {
if (conditionIds.length != indices.length) revert InvalidIndex();
uint256 totalBurnt = 0;
uint256[] memory eventIndices = new uint256[](1);
for (uint256 i = 0; i < conditionIds.length; i++) {
ConditionID conditionId = conditionIds[i];
uint256 index = indices[i];
uint256 positionId = CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(conditionId, index));
uint256 burnAmount = balanceOf(ownerAndReceiver, positionId);
totalBurnt += burnAmount;
uint256 payout = _redeemPosition(ownerAndReceiver, positionId, conditionId, index, burnAmount);
totalPayout += payout;
eventIndices[0] = index;
emit PayoutRedemption(ownerAndReceiver, collateralToken, conditionId, eventIndices, payout);
}
if (totalBurnt == 0) {
revert NoPositionsToRedeem();
}
if (totalPayout > 0) {
collateralToken.safeTransfer(ownerAndReceiver, totalPayout);
}
}
/// @notice Returns the balance array of conditional tokens (ERC1155) of an account for a particular condition ID.
/// @param account account address to query for balances.
/// @param collateralToken collateral token associated with the position ID.
/// @param conditionId condition ID to query for.
function balanceOfCondition(address account, IERC20 collateralToken, ConditionID conditionId)
public
view
returns (uint256[] memory)
{
uint256 outcomeSlotCount = payoutNumerators[conditionId].length;
if (outcomeSlotCount == 0) revert ConditionNotFound();
uint256[] memory batchBalances = new uint256[](outcomeSlotCount);
for (uint256 i = 0; i < outcomeSlotCount; ++i) {
uint256 positionId = CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(conditionId, i));
batchBalances[i] = balanceOf(account, positionId);
}
return batchBalances;
}
/// @dev Gets the number of outcome slots for a condition ID.
/// @param conditionId ID of the condition.
/// @return outcomeSlotCount Number of outcome slots associated with a condition, or zero if condition has not been
/// prepared yet.
function getOutcomeSlotCount(ConditionID conditionId) public view returns (uint256 outcomeSlotCount) {
outcomeSlotCount = payoutNumerators[conditionId].length;
}
/// @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 for this condition. Must not exceed 256.
function getConditionId(address oracle, QuestionID questionId, uint256 outcomeSlotCount)
external
pure
returns (ConditionID)
{
return CTHelpers.getConditionId(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) public pure returns (CollectionID) {
return CTHelpers.getCollectionId(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) external pure returns (uint256) {
return CTHelpers.getPositionId(collateralToken, collectionId);
}
/// @dev Constructs list of positionIds for a condition. These IDs are used as the ERC-1155 ID for this contract.
/// @param collateralToken Collateral token which backs the position.
/// @param conditionId ID of the condition
function getPositionIds(IERC20 collateralToken, ConditionID conditionId) external view returns (uint256[] memory) {
uint256 outcomeSlotCount = getOutcomeSlotCount(conditionId);
uint256[] memory positionIds = new uint256[](outcomeSlotCount);
for (uint256 i = 0; i < outcomeSlotCount; i++) {
positionIds[i] = CTHelpers.getPositionId(collateralToken, getCollectionId(conditionId, i));
}
return positionIds;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
type QuestionID is bytes32;
type ConditionID is bytes32;
type CollectionID is bytes32;
/// @dev Stores up to 32 outcome indices in a single bytes32 value. Length
/// should be stored elsewhere
type PackedIndices is bytes32;
library CTHelpers {
/// @dev Constructs a condition ID from an oracle, a question ID, and the
/// outcome slot count for the question.
/// @param oracle The account assigned to report the result for the prepared condition.
/// @param questionId An identifier for the question to be answered by the oracle.
/// @param outcomeSlotCount The number of outcome slots which should be used
/// for this condition. Must not exceed 256.
function getConditionId(address oracle, QuestionID questionId, uint256 outcomeSlotCount)
internal
pure
returns (ConditionID)
{
assert(outcomeSlotCount < 257); // `<` uses less gas than `<=`
return ConditionID.wrap(keccak256(abi.encodePacked(oracle, questionId, outcomeSlotCount)));
}
/// @dev Constructs an outcome collection ID
/// @param conditionId Condition ID of the outcome collection
/// @param index outcome index
function getCollectionId(ConditionID conditionId, uint256 index) internal pure returns (CollectionID) {
return CollectionID.wrap(keccak256(abi.encodePacked(conditionId, index)));
}
/// @dev Constructs a position ID from a collateral token and an outcome
/// collection. These IDs are used as the ERC-1155 ID for this contract.
/// @param collateralToken Collateral token which backs the position.
/// @param collectionId ID of the outcome collection associated with this position.
function getPositionId(IERC20 collateralToken, CollectionID collectionId) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(collateralToken, collectionId)));
}
/// @dev Constructs all position ID in a condition, for a collateral token.
/// These IDs are used as the ERC-1155 ID for the ConditionalTokens contract.
/// @param collateralToken Collateral token which backs the position.
/// @param conditionId ID of the condition associated with all positions
/// @param outcomeSlotCount number of outcomes in the condition
function getPositionIds(IERC20 collateralToken, ConditionID conditionId, uint256 outcomeSlotCount)
internal
pure
returns (uint256[] memory positionIds)
{
positionIds = new uint256[](outcomeSlotCount);
for (uint256 i = 0; i < outcomeSlotCount; i++) {
positionIds[i] = getPositionId(collateralToken, getCollectionId(conditionId, i));
}
}
function encodeIndices(uint256[] memory indices) internal pure returns (PackedIndices) {
bytes32 packedIndices;
uint256 length = indices.length;
unchecked {
for (uint256 i; i < length; i++) {
uint256 value = indices[i];
assert(value <= type(uint8).max);
packedIndices |= bytes32(value << (8 * i));
}
}
return PackedIndices.wrap(packedIndices);
}
function getIndex(PackedIndices indices, uint256 i) internal pure returns (uint256) {
return (uint256(PackedIndices.unwrap(indices)) >> (8 * i)) & 0xff;
}
function decodeIndices(PackedIndices packedIndices, uint256 length)
internal
pure
returns (uint256[] memory indices)
{
unchecked {
indices = new uint256[](length);
for (uint256 i; i < length; i++) {
indices[i] = getIndex(packedIndices, i);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
/// @dev Functions to deal with 16bit prices packed into `bytes`.
/// In prediction markets, prices are within the range [0-1]. As such, arbitrary
/// magnitude and precision are not necessary. By restricting prices to be fixed
/// point integers between 0 and 1e4, we get:
/// - Prices fit in 16 bits
/// - Can be easily renormalized to 1e18 via a multiplier
///
/// The 16bit prices are packed back to back and encoded in big-endian format.
///
/// Some notes:
///
/// Packing/unpacking is done manually and not via solidity's uint16[].
/// uint16[] arrays are still encoded with all the padding. Additionally,
/// working directly with uint16 data types is less efficient than uint256, due
/// to bit shifting and masking that is implicitly done
library PackedPrices {
using Math for uint256;
/// @dev a divisor that fits in 16 bits, and easily divides into 1e18
uint256 internal constant DIVISOR = 1e4;
/// @dev divisor for majority of decimal calculations
uint256 internal constant ONE_DECIMAL = 1e18;
/// @dev We store packed prices in 16 bits with a divisor of 1e4. AMM math
/// relies on prices having divisor of 1e18. We can go directly from one to
/// the other by multiplying by 1e14.
uint256 internal constant DECIMAL_CONVERSION_FACTOR = 1e14;
/// @dev How many bits to shift to convert between big-endian uint16 and uint256
uint256 internal constant SHIFT_BITS = 30 * 8;
/// @dev Given a packed price byte array, unpack into a decimal price array with 1e18 divisor
/// @param packedPrices packed byte array
/// @return priceDecimals unpacked price array of prices normalized to 1e18
function toPriceDecimals(bytes memory packedPrices) internal pure returns (uint256[] memory priceDecimals) {
unchecked {
uint256 length = packedPrices.length / 2;
priceDecimals = new uint256[](length);
for (uint256 i; i < length; i++) {
uint256 chunk;
uint256 offset = 32 + i * 2;
assembly ("memory-safe") {
chunk := mload(add(packedPrices, offset))
}
priceDecimals[i] = (chunk >> SHIFT_BITS) * DECIMAL_CONVERSION_FACTOR;
}
}
}
/// @dev Given a packed price byte array in storage, unpack into a decimal price array with 1e18 divisor
/// @param packedPrices packed byte array storage pointer
/// @return priceDecimals unpacked price array of prices normalized to 1e18
function toPriceDecimalsFromStorage(bytes storage packedPrices) internal pure returns (uint256[] memory) {
// Much easier to copy the byte array into memory first, and then
// perform the conversion from memory array, than doing it directly from
// storage.
// This is because the storage load instruction `SLOAD` costs 200 gas,
// while the memory load instruction `MLOAD` costs only 3. The
// drastically simpler code that loads each integer one at a time would
// be extremely costly with SLOAD, and would require a different
// algorithm that amounts to copying into memory first to minimize SLOAD
// instructions.
return toPriceDecimals(packedPrices);
}
/// @dev Given an array of integers, packs them into a byte array of 16bit values.
/// Integers are taken as-is, with no re-normalization.
/// @param prices array of integers less than or equal to type(uint16).max . Otherwise truncation will occur
/// @param divisor what to divide prices by before packing
/// @return packedPrices packed byte array
function toPackedPrices(uint256[] memory prices, uint256 divisor)
internal
pure
returns (bytes memory packedPrices)
{
unchecked {
uint256 length = prices.length;
// set the size of bytes array
packedPrices = new bytes(length * 2);
for (uint256 i; i < length; i++) {
uint256 adjustedPrice = prices[i] / divisor;
assert(adjustedPrice <= type(uint16).max);
uint256 chunk = adjustedPrice << SHIFT_BITS;
uint256 offset = 32 + i * 2;
assembly {
mstore(add(packedPrices, offset), chunk)
}
}
}
}
/// @dev Sums the values in the packed price byte array
/// @param packedPrices the byte array that encodes the packed prices
/// @return result the sum of the decoded prices
function sum(bytes memory packedPrices) internal pure returns (uint256 result) {
unchecked {
uint256 length = packedPrices.length / 2;
for (uint256 i; i < length; i++) {
uint256 chunk;
uint256 offset = 32 + i * 2;
assembly ("memory-safe") {
chunk := mload(add(packedPrices, offset))
}
result += chunk >> SHIFT_BITS;
}
}
}
function arrayLength(bytes memory packedPrices) internal pure returns (uint256) {
return packedPrices.length / 2;
}
function valueAtIndex(bytes memory packedPrices, uint256 index) internal pure returns (uint256) {
uint256 chunk;
uint256 offset = 32 + index * 2;
assembly ("memory-safe") {
chunk := mload(add(packedPrices, offset))
}
return (chunk >> SHIFT_BITS);
}
}
// 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
// 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/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155Upgradeable.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated 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 v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized < type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import { 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
);
/// @notice Emitted when a redemption occurs where the proceeds are given to a different address
event PayoutRedemptionFor(
address indexed receiver,
address indexed redeemer,
IERC20 indexed collateralToken,
ConditionID conditionId,
uint256[] indices,
uint256[] quantities,
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);
/// @dev number of outcome slots in a condition
function getOutcomeSlotCount(ConditionID conditionId) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) 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[50] private __gap;
}
// 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
pragma solidity ^0.8.19;
// Note on libraries. If any functions are not `internal`, then contracts that
// use the libraries, must be linked.
library ArrayMath {
function sum(uint256[] memory values) internal pure returns (uint256) {
uint256 result = 0;
for (uint256 i = 0; i < values.length; i++) {
result += values[i];
}
return result;
}
}
/// @dev Math with saturation/clamping for overflow/underflow handling
library ClampedMath {
/// @dev min(upper, max(lower, x))
function clampBetween(uint256 x, uint256 lower, uint256 upper) internal pure returns (uint256) {
unchecked {
return x < lower ? lower : (x > upper ? upper : x);
}
}
/// @dev max(0, a - b)
function subClamp(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
return a > b ? a - b : 0;
}
}
/// @dev min(type(uint256).max, max(0, a + b))
function addClamp(uint256 a, int256 b) internal pure returns (uint256) {
unchecked {
if (b < 0) {
// The absolute value of type(int256).min is not representable
// in int256, so have to dance about with the + 1
uint256 positiveB = uint256(-(b + 1)) + 1;
return (a > positiveB) ? (a - positiveB) : 0;
} else {
return type(uint256).max - a > uint256(b) ? a + uint256(b) : type(uint256).max;
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
interface ConditionalTokensErrors {
error ConditionAlreadyPrepared();
error PayoutAlreadyReported();
error PayoutsAreAllZero();
error InvalidOutcomeSlotCountsArray();
error InvalidPayoutArray();
error ResultNotReceivedYet();
error InvalidIndex();
error NoPositionsToRedeem();
error ConditionNotFound();
error InvalidAmount();
error InvalidOutcomeSlotsAmount();
error InvalidQuantities();
error InvalidPrices();
error InvalidConditionOracle(address conditionOracle);
error MustBeCalledByOracle();
error InvalidHaltTime();
/// @dev using unapproved ERC20 token with protocol
error InvalidERC20();
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822ProxiableUpgradeable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.3) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/IERC1967Upgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable {
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @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) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @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 v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (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 v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.3) (interfaces/IERC1967.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*
* _Available since v4.9._
*/
interface IERC1967Upgradeable {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
}