Blockchain / Global / Address
Contract
0x949d971e8A6f70807B1cecb698AE7b5D558128F2
- Balance
- 0 SOMI
- Transactions sent
- 1
- Type
- Contract · 34,152 bytes of code
PredictionMarketCore Verified
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- Solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- —
- Verified
- 2026-10-12
src/PredictionMarketCore.sol
and 60 more files
Solidity
// SPDX-License-Identifier: LGPL-3.0
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {ERC1155HolderUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {EIP712Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import {MulticallUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol";
import {ConditionalTokens} from "./ConditionalTokens.sol";
import {OrderRouter} from "./OrderRouter.sol";
import {CTHelpers} from "./CTHelpers.sol";
import {VenueRegistry} from "./VenueRegistry.sol";
import {IVenuePolicy} from "./interfaces/IVenuePolicy.sol";
import {IOracleAdapter} from "./interfaces/IOracleAdapter.sol";
import {IOracleAnswerReceiver} from "./interfaces/IOracleAnswerReceiver.sol";
import {IWETH9} from "./interfaces/IWETH9.sol";
import {ISignatureTransfer} from "./interfaces/ISignatureTransfer.sol";
import {QuestionDefinition} from "./types/OracleTypes.sol";
/// @title PredictionMarketCore
/// @notice User-facing facade for the protocol. Every market is bound 1:1
/// to an oracle question via an `IOracleAdapter`. Resolution is
/// automatic via the adapter's reactivity subscription (or a
/// `pokeOracle` pull fallback). There is no manual oracle path.
///
/// Every routed call is tagged with a `venueId` (0 = no venue, no
/// fee, no signature). Registered venues capture a trade-time fee
/// skimmed in collateral on buy/sell, and may require an off-chain
/// EIP-712 signature gate on any of their attributed calls.
contract PredictionMarketCore is ERC1155HolderUpgradeable, ReentrancyGuardUpgradeable, EIP712Upgradeable, IOracleAnswerReceiver, UUPSUpgradeable, Ownable2StepUpgradeable, MulticallUpgradeable {
using SafeERC20 for IERC20;
error UnknownMarket();
error MaxAmountExceeded();
error UnknownOracleQuestion();
error OutcomeCountMismatch();
error NotAuthorizedAdapter();
error AdapterNotApproved();
error WithdrawFailed();
error ZeroLiquidity();
error FeeExceedsMax();
error VenueAuthExpired();
error VenueNonceUsed();
error VenueSignerUnset();
error InvalidVenueSignature();
error VenuePolicyDenied();
error InvalidAdapter();
error OracleNotAnswered();
error InvalidOutcomeIndex();
error TooManyMarketsForQuestion();
error NativeNotSupported();
error NativeAmountMismatch();
error NativeTransferFailed();
error Permit2NotConfigured();
error ZeroAddress();
error InvalidTradingWindow();
error InvalidFee();
error InvalidPermitToken();
error LiquidityFrozen();
error UnderpaidScheduleFee();
error EthRefundFailed();
error RedeemAuthExpired();
error RedeemNonceUsed();
error RedeemSignatureInvalid();
error ClaimFeesAuthExpired();
error ClaimFeesNonceUsed();
error ClaimFeesSignatureInvalid();
enum VoidPolicy {
UNIFORM,
AMM_SNAPSHOT
}
/// @dev Intermediate values produced during market setup. Packed into a memory
/// struct so that _createMarket's stack frame stays within the Yul 16-slot limit.
struct _MarketPrep {
uint8 slots;
uint256 marketIndex;
bytes32 questionIdCt;
bytes32 conditionId;
}
/// @dev With 1:1 condition↔market, marketId == conditionId. We store
/// everything needed to resolve and to surface UI state. Each market
/// has its own per-market FPMM clone address stored in `market`.
/// @dev Append-only: never reorder or remove fields. New fields go at the
/// end so pre-upgrade records continue to decode and the new tail
/// reads as zero / empty for them.
struct MarketRecord {
uint256 oracleQuestionId;
bytes32 questionId; // keccak256(abi.encode(oracleQuestionId, marketIndex)), passed to CT
uint8 outcomeSlotCount;
VoidPolicy voidPolicy;
IERC20 collateralToken;
uint256 fee; // 1e18-scaled LP fee from createPool
uint256 _deprecatedExpectedResolutionTime; // Deprecated: reserved to maintain storage layout
uint32 originVenueId; // venue that created the market (attribution only in v1)
IOracleAdapter oracleAdapter; // adapter that resolves this market
address creator; // wallet that called createMarket
uint16 creatorFeeBps; // trade-time fee to creator, 1e4-scaled bps
address market; // per-market FPMM clone address
uint64 tradingClose; // unix timestamp when trading closes (0 = no close)
bytes metadata; // opaque creator-supplied blob (category, image hash, source URL, ...)
}
/// @notice Off-chain venue authorization. Consulted on market-creation
/// entry points when the routed venue has `requiresCreateSig`,
/// and on buy/sell when the venue has `requiresTradeSig`. The
/// flags are independent so a venue can gate only the path it
/// cares about. Liquidity, redeem, and withdrawFees never
/// require a signature. Replay-protected by (venueId, nonce);
/// `deadline` is a unix timestamp.
struct VenueAuth {
uint256 nonce;
uint256 deadline;
bytes signature;
}
struct TradeAuth {
address routingFeeRecipient;
uint16 routingFeeBps;
address marketFeeRecipient;
uint16 marketFeeBps;
}
/// @notice Pre-PRP-645 `MarketCreated` event, kept alongside the 14-arg
/// variant so consumers still holding the historic ABI (topic0
/// `0xf9c0d218…`) keep decoding new markets. Emitted from
/// `_emitCreated` before the current-shape event. The indexer
/// registers this signature under the `MarketCreatedLegacy`
/// alias — see `indexer/config.yaml`.
event MarketCreated(
bytes32 indexed conditionId,
address indexed market,
uint256 indexed oracleQuestionId,
uint32 venueId,
address creator,
address collateralToken,
uint256 fee,
uint8 outcomeSlotCount,
uint256 tradingStart,
uint256 tradingClose,
VoidPolicy voidPolicy,
uint256 marketIndex,
uint16 creatorFeeBps
);
/// @notice Current MarketCreated event carrying the opaque `metadata`
/// blob (PRP-645). Emitted from `_emitCreated` after the legacy
/// event. The indexer decodes the metadata field from this event.
event MarketCreated(
bytes32 indexed conditionId,
address indexed market,
uint256 indexed oracleQuestionId,
uint32 venueId,
address creator,
address collateralToken,
uint256 fee,
uint8 outcomeSlotCount,
uint256 tradingStart,
uint256 tradingClose,
VoidPolicy voidPolicy,
uint256 marketIndex,
uint16 creatorFeeBps,
bytes metadata
);
/// @notice Fired when an oracle answer triggers resolution (either via
/// the adapter's reactivity callback or pokeOracle).
event MarketResolved(
bytes32 indexed conditionId,
uint256 indexed oracleQuestionId,
uint8 outcomeIdx,
bool voided,
uint256[] payouts
);
/// @notice Router-level trade events. The indexer uses these (rather
/// than the CPMM's own Buy/Sell) as the canonical Trade record
/// because they carry the venueId + the venue fee paid.
/// Reserves are still derived from the CPMM events.
event RouterBuy(
bytes32 indexed conditionId,
address indexed trader,
uint32 indexed venueId,
uint256 indexSet,
uint256 investmentAmount, // user-facing input
uint256 outcomeTokensBought,
uint256 lpFee, // fee absorbed by CPMM (LP pool)
uint256 venueFee, // skimmed by router to routing venue feeRecipient
uint256 marketVenueFee, // skimmed to origin venue feeRecipient
uint256 creatorFee // skimmed to market creator
);
event RouterSell(
bytes32 indexed conditionId,
address indexed trader,
uint32 indexed venueId,
uint256 outcomeIndex,
uint256 returnAmount, // amount CPMM returned to router
uint256 amountToTrader, // returnAmount - all fees
uint256 outcomeTokensSold,
uint256 lpFee,
uint256 venueFee,
uint256 marketVenueFee,
uint256 creatorFee
);
event RouterAddLiquidity(
bytes32 indexed conditionId, address indexed funder, uint32 indexed venueId, uint256 amount, uint256 shares
);
event RouterRemoveLiquidity(
bytes32 indexed conditionId, address indexed funder, uint32 indexed venueId, uint256 shares
);
event RouterRedeem(bytes32 indexed conditionId, address indexed redeemer, uint32 indexed venueId);
/// @notice Emitted when a user mints a complete set of outcome tokens
/// (collateral → one of every outcome). No fee — 1:1 conversion.
event RouterMintCompleteSet(
bytes32 indexed conditionId, address indexed user, uint32 indexed venueId, uint256 amount
);
/// @notice Emitted when a user merges a complete set back into collateral.
/// Inverse of `RouterMintCompleteSet`. No fee.
event RouterMergeCompleteSet(
bytes32 indexed conditionId, address indexed user, uint32 indexed venueId, uint256 amount
);
event RouterWithdrawFees(bytes32 indexed conditionId, address indexed lp, uint32 indexed venueId);
event AdapterApproved(address indexed adapter, bool approved);
event MarketResolutionSkipped(bytes32 indexed conditionId, uint8 outcomeIdx, uint8 slots);
ConditionalTokens public CONDITIONAL_TOKENS;
OrderRouter public ORDER_ROUTER;
VenueRegistry public VENUE_REGISTRY;
IWETH9 public wNative;
address public PERMIT2;
event Deposited(address indexed from, uint256 amount);
event Withdrawn(address indexed to, uint256 amount);
/// @dev EIP-712 typehash for venue-signed authorizations.
bytes32 public constant VENUE_AUTH_TYPEHASH =
keccak256("VenueAuthorization(uint32 venueId,address user,bytes32 callHash,uint256 nonce,uint256 deadline)");
bytes32 public constant REDEEM_AUTH_TYPEHASH =
keccak256("RedeemAuthorization(address owner,uint32 venueId,bytes32 conditionId,uint256[] indexSets,uint256 nonce,uint256 deadline)");
bytes32 public constant CLAIM_FEES_AUTH_TYPEHASH =
keccak256("ClaimFeesAuthorization(address owner,uint32 venueId,bytes32[] conditionIds,uint256 nonce,uint256 deadline)");
uint16 public constant MAX_CREATOR_FEE_BPS = 500;
uint256 internal constant WAD = 1e18;
uint256 internal constant BPS_DENOMINATOR = 10000;
uint256 internal constant MAX_MARKETS_PER_QUESTION = 64;
/// @dev conditionId == marketId => MarketRecord.
mapping(bytes32 => MarketRecord) public markets;
/// @dev 1:many reverse lookup: all conditionIds bound to a given oracle question.
/// Lets the adapter's onOracleAnswer callback resolve all markets for a question in O(n).
mapping(uint256 => bytes32[]) public conditionIdsForOracleQuestion;
/// @notice Replay protection for venue-signed authorizations. Scoped
/// per (venueId, user, nonce) so each caller has their own
/// independent nonce space — venues don't need to coordinate
/// nonces across users.
mapping(uint32 => mapping(address => mapping(uint256 => bool))) public venueNonceUsed;
/// @dev Number of markets registered per oracle question (used as nonce for conditionId derivation).
mapping(uint256 => uint256) public marketCountFor;
/// @notice Whitelist of approved IOracleAdapter contracts. Only approved adapters
/// may call onOracleAnswer and may be used to create markets.
mapping(address => bool) public approvedAdapters;
/// @notice Replay protection for redeemFor EIP-712 authorizations. Scoped per (owner, nonce).
mapping(address => mapping(uint256 => bool)) public redeemNonceUsed;
/// @notice Replay protection for claimFeesFor EIP-712 authorizations. Scoped per (owner, nonce).
mapping(address => mapping(uint256 => bool)) public claimFeesNonceUsed;
uint256[38] private __gap;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() { _disableInitializers(); }
/// @notice Initialise the proxy. Called once immediately after the ERC1967Proxy is created.
/// @param conditionalTokens_ ConditionalTokens contract that mints/burns ERC-1155 outcome positions.
/// @param orderRouter_ OrderRouter that manages per-market FPMM clones.
/// @param venueRegistry_ VenueRegistry for fee and policy lookups.
/// @param wNative_ Wrapped-native ERC-20 (e.g. wSTT); zero address disables native-token paths.
/// @param admin_ Initial owner; receives upgrade and admin privileges.
/// @param permit2_ Canonical Permit2 address; zero address disables Permit2 paths.
function initialize(
ConditionalTokens conditionalTokens_,
OrderRouter orderRouter_,
VenueRegistry venueRegistry_,
IWETH9 wNative_,
address admin_,
address permit2_
) external initializer {
__ERC1155Holder_init();
__ReentrancyGuard_init();
__EIP712_init("ProphecyRouter", "1");
__Ownable_init(admin_);
__UUPSUpgradeable_init();
__Multicall_init();
if (address(conditionalTokens_) == address(0)) revert ZeroAddress();
if (address(orderRouter_) == address(0)) revert ZeroAddress();
if (address(venueRegistry_) == address(0)) revert ZeroAddress();
if (admin_ == address(0)) revert ZeroAddress();
CONDITIONAL_TOKENS = conditionalTokens_;
ORDER_ROUTER = orderRouter_;
VENUE_REGISTRY = venueRegistry_;
wNative = wNative_;
PERMIT2 = permit2_;
// Allow OrderRouter to pull outcome tokens from this contract during sell.
IERC1155(address(conditionalTokens_)).setApprovalForAll(address(orderRouter_), true);
}
function _authorizeUpgrade(address) internal override onlyOwner {}
// ---- Native-balance management ---------------------------------------
//
// The contract accepts native token deposits and lets the owner withdraw.
// Any accidentally deposited native ETH is recoverable via `withdraw(0, to)`.
receive() external payable {
// Suppress Deposited for wNative.withdraw() callbacks — transient unwraps
// from _pushCollateral, not protocol deposits.
if (address(wNative) == address(0) || msg.sender != address(wNative)) {
emit Deposited(msg.sender, msg.value);
}
}
/// @notice Rescue ERC-20 tokens accidentally sent to this contract.
/// @param token ERC-20 to sweep; the full balance is transferred.
/// @param to Recipient; must be non-zero.
function sweepERC20(IERC20 token, address to) external onlyOwner {
if (to == address(0)) revert ZeroAddress();
uint256 bal = token.balanceOf(address(this));
if (bal > 0) token.safeTransfer(to, bal);
}
/// @notice Withdraw native balance to `to`. Pass amount=0 to drain the full balance.
/// @param amount Wei to withdraw; 0 drains the entire contract balance.
/// @param to Recipient; must be non-zero and able to receive native token.
function withdraw(uint256 amount, address payable to) external onlyOwner {
if (to == address(0)) revert ZeroAddress();
uint256 wd = amount == 0 ? address(this).balance : amount;
(bool ok,) = to.call{value: wd}("");
if (!ok) revert WithdrawFailed();
emit Withdrawn(to, wd);
}
// ---- Adapter registry ------------------------------------------------
/// @notice Approve or revoke an oracle adapter. Only approved adapters can be used
/// to create markets or call onOracleAnswer.
/// @param adapter Address of the IOracleAdapter implementation; must be non-zero.
/// @param approved True to whitelist; false to revoke.
function setAdapterApproved(address adapter, bool approved) external onlyOwner {
if (adapter == address(0)) revert ZeroAddress();
approvedAdapters[adapter] = approved;
emit AdapterApproved(adapter, approved);
}
// ---- ERC-165 ---------------------------------------------------------
/// @notice Returns true for IOracleAnswerReceiver, ERC-1155 receiver, and ERC-165.
/// @return True if this contract implements the queried interface.
function supportsInterface(bytes4 interfaceId) public view override(ERC1155HolderUpgradeable, IERC165) returns (bool) {
return interfaceId == type(IOracleAnswerReceiver).interfaceId || super.supportsInterface(interfaceId);
}
// ---- Discovery -------------------------------------------------------
/// @notice Returns the per-market FPMM clone address for a known market.
/// @param conditionId Market condition ID.
/// @return market Address of the FPMM clone; reverts with UnknownMarket if not registered.
function marketAddress(bytes32 conditionId) public view returns (address market) {
if (markets[conditionId].outcomeSlotCount == 0) revert UnknownMarket();
return markets[conditionId].market;
}
/// @notice Compute the conditionId for a given oracle question and market index.
/// conditionId = keccak256(address(this), keccak256(oracleQuestionId, marketIndex), outcomeSlotCount).
/// marketIndex lets multiple independent markets share the same oracle question without sharing positions.
/// @param oracleQuestionId Numeric question ID as stored in the adapter's oracle.
/// @param outcomeSlotCount Number of discrete outcomes; must match the adapter's `getSlotCount` return.
/// @param marketIndex Zero-based market index; equals `marketCountFor[oracleQuestionId]` at creation time.
/// @return Deterministic condition ID used as the primary market key throughout the protocol.
function conditionIdFor(uint256 oracleQuestionId, uint8 outcomeSlotCount, uint256 marketIndex) public view returns (bytes32) {
bytes32 questionIdCt = keccak256(abi.encode(oracleQuestionId, marketIndex));
return CTHelpers.getConditionId(address(this), questionIdCt, outcomeSlotCount);
}
// ---- Venue resolution / auth ----------------------------------------
/// @dev Authorize a market-creation call. Runs the venue's `canCreateMarket`
/// policy hook (if set), then verifies the EIP-712 signature when the
/// venue has `requiresCreateSig = true`. venueId==0 and venues without
/// `requiresCreateSig` skip verification entirely.
function _authorizeCreate(uint32 venueId, bytes32 callHash, VenueAuth calldata auth) internal {
if (venueId == 0) return;
(, address signer,, bool requiresCreateSig,, IVenuePolicy policy) =
VENUE_REGISTRY.venueForRoutingFull(venueId);
if (address(policy) != address(0) && !policy.canCreateMarket(msg.sender)) {
revert VenuePolicyDenied();
}
if (!requiresCreateSig) return;
_verifyVenueSig(venueId, callHash, auth, signer);
}
/// @dev Authorize a buy/sell call and return trade auth data. Fetches
/// the routing venue's data (including policy) in a single registry
/// call, runs `canTrade` and the origin's `canRoute` hooks, then
/// verifies the EIP-712 signature when required. venueId==0
/// short-circuits routing-venue checks but the origin's `canRoute`
/// still applies.
function _authorizeTrade(uint32 venueId, bytes32 conditionId, bytes32 callHash, VenueAuth calldata auth)
internal
returns (TradeAuth memory ta)
{
uint32 originVenueId = markets[conditionId].originVenueId;
IVenuePolicy originPolicy;
if (originVenueId != 0) {
IVenuePolicy p;
(ta.marketFeeRecipient, ta.marketFeeBps, p) = VENUE_REGISTRY.marketFeeInfoFull(originVenueId);
originPolicy = p;
}
if (venueId == 0) {
if (address(originPolicy) != address(0) && !originPolicy.canRoute(0, conditionId)) {
revert VenuePolicyDenied();
}
return ta;
}
(address fr, address signer, uint16 fee,, bool requiresTradeSig, IVenuePolicy routingPolicy) =
VENUE_REGISTRY.venueForRoutingFull(venueId);
if (address(routingPolicy) != address(0) && !routingPolicy.canTrade(msg.sender, conditionId)) {
revert VenuePolicyDenied();
}
if (originVenueId != 0 && originVenueId != venueId) {
if (address(originPolicy) != address(0) && !originPolicy.canRoute(venueId, conditionId)) {
revert VenuePolicyDenied();
}
}
ta.routingFeeRecipient = fr;
ta.routingFeeBps = fee;
if (!requiresTradeSig) return ta;
_verifyVenueSig(venueId, callHash, auth, signer);
}
/// @dev Shared EIP-712 verification path. Marks the (venueId, nonce) used
/// on success so the same authorization can't be replayed.
function _verifyVenueSig(uint32 venueId, bytes32 callHash, VenueAuth calldata auth, address signer) internal {
if (signer == address(0)) revert VenueSignerUnset();
if (block.timestamp > auth.deadline) revert VenueAuthExpired();
if (venueNonceUsed[venueId][msg.sender][auth.nonce]) revert VenueNonceUsed();
bytes32 structHash =
// forge-lint: disable-next-line(asm-keccak256)
keccak256(abi.encode(VENUE_AUTH_TYPEHASH, venueId, msg.sender, callHash, auth.nonce, auth.deadline));
bytes32 digest = _hashTypedDataV4(structHash);
if (!SignatureChecker.isValidSignatureNow(signer, digest, auth.signature)) revert InvalidVenueSignature();
venueNonceUsed[venueId][msg.sender][auth.nonce] = true;
}
// ---- Lifecycle -------------------------------------------------------
struct CreateMarketParams {
uint256 oracleQuestionId;
IOracleAdapter oracleAdapter; // must be approved via setAdapterApproved
IERC20 collateral;
uint256 fee;
uint256 tradingStart;
uint256 tradingClose;
VoidPolicy voidPolicy;
uint16 creatorFeeBps; // fee creator charges on every trade; 0 = no creator fee
/// @dev Opaque creator-supplied blob — stored on `MarketRecord.metadata`
/// and emitted on `MarketCreated`. Intended for off-chain context
/// such as a category tag, image hash, source URL, or scoring rule
/// hint. The protocol does not interpret it; format is up to the
/// venue/UI. Pass empty bytes to opt out.
bytes metadata;
}
/// @notice Bind a new market to an existing oracle question.
/// The adapter must already be approved via `setAdapterApproved`.
/// @param venueId Attribution and fee routing; 0 = no venue.
/// @param p Market configuration; see `CreateMarketParams`.
/// @param auth Venue authorization; only consulted when the venue has `requiresCreateSig`.
/// @return conditionId Primary market key, derived from the oracle question and market index.
/// @return market Address of the freshly deployed FPMM clone.
function createMarket(uint32 venueId, CreateMarketParams calldata p, VenueAuth calldata auth)
external
returns (bytes32 conditionId, address market)
{
// msg.sig instead of `this.createMarket.selector` because the legacy shim
// below overloads the name — `.selector` would be ambiguous.
// forge-lint: disable-next-line(asm-keccak256)
bytes32 callHash = keccak256(abi.encode(msg.sig, venueId, p));
_authorizeCreate(venueId, callHash, auth);
CreateMarketParams memory pm = p;
return _createMarket(pm, msg.sender, venueId);
}
/// @notice Bind a new market AND seed initial liquidity in one tx.
/// Requires caller to have approved `initialFunding` of the
/// collateral to this router. Reverts if `initialFunding == 0`.
/// @param venueId Attribution and fee routing; 0 = no venue.
/// @param p Market configuration; see `CreateMarketParams`.
/// @param initialFunding Collateral amount to deposit as initial liquidity; must be > 0.
/// @param context ABI-encoded `uint256[]` distribution hint for the initial price skew.
/// @param auth Venue authorization; only consulted when the venue has `requiresCreateSig`.
/// @return conditionId Primary market key.
/// @return market Address of the freshly deployed FPMM clone.
/// @return positionData ABI-encoded `uint256` LP shares minted to `msg.sender`.
function createMarketAndSeed(
uint32 venueId,
CreateMarketParams calldata p,
uint256 initialFunding,
bytes calldata context,
VenueAuth calldata auth
)
external
returns (bytes32 conditionId, address market, bytes memory positionData)
{
if (initialFunding == 0) revert ZeroLiquidity();
bytes32 callHash =
// forge-lint: disable-next-line(asm-keccak256)
keccak256(abi.encode(msg.sig, venueId, p, initialFunding, context));
_authorizeCreate(venueId, callHash, auth);
CreateMarketParams memory pm = p;
(conditionId, market) = _createMarket(pm, msg.sender, venueId);
positionData = _seedLiquidity(conditionId, p.collateral, initialFunding, context);
uint256 sharesMinted = abi.decode(positionData, (uint256));
emit RouterAddLiquidity(conditionId, msg.sender, venueId, initialFunding, sharesMinted);
}
/// @notice Schedule an oracle question and create a market for it in one transaction.
/// The `adapter` must already be approved via `setAdapterApproved`. The
/// scheduling fee is sent via `msg.value`; any excess is refunded to the caller.
/// `p.oracleQuestionId` in the calldata is ignored — the scheduled id is used.
/// @param venueId Attribution and fee routing; 0 = no venue.
/// @param adapter Approved IOracleAdapter to schedule the question through.
/// @param def Full question definition forwarded to the adapter's oracle.
/// @param p Market configuration; `oracleQuestionId` field is overwritten.
/// @param auth Venue authorization.
/// @return oracleQuestionId Oracle-assigned ID for the scheduled question.
/// @return conditionId Primary market key.
/// @return market Address of the freshly deployed FPMM clone.
function scheduleAndCreateMarket(
uint32 venueId,
IOracleAdapter adapter,
QuestionDefinition calldata def,
CreateMarketParams calldata p,
VenueAuth calldata auth
)
external
payable
returns (uint256 oracleQuestionId, bytes32 conditionId, address market)
{
{
// forge-lint: disable-next-line(asm-keccak256)
bytes32 callHash = keccak256(abi.encode(msg.sig, venueId, address(adapter), def, p));
_authorizeCreate(venueId, callHash, auth);
}
oracleQuestionId = _scheduleAndRefund(adapter, def);
CreateMarketParams memory pm = p;
pm.oracleQuestionId = oracleQuestionId;
pm.oracleAdapter = adapter;
(conditionId, market) = _createMarket(pm, msg.sender, venueId);
}
/// @notice Schedule an oracle question, create a market for it, and seed initial
/// liquidity — all in one transaction. Scheduling fee via `msg.value`;
/// excess refunded. Reverts if `initialFunding == 0`.
/// @param venueId Attribution and fee routing; 0 = no venue.
/// @param adapter Approved IOracleAdapter to schedule the question through.
/// @param def Full question definition forwarded to the adapter's oracle.
/// @param p Market configuration; `oracleQuestionId` field is overwritten.
/// @param initialFunding Collateral amount to deposit as initial liquidity; must be > 0.
/// @param context ABI-encoded `uint256[]` distribution hint for the initial price skew.
/// @param auth Venue authorization.
/// @return oracleQuestionId Oracle-assigned ID for the scheduled question.
/// @return conditionId Primary market key.
/// @return market Address of the freshly deployed FPMM clone.
/// @return positionData ABI-encoded `uint256` LP shares minted to `msg.sender`.
function scheduleCreateAndSeed(
uint32 venueId,
IOracleAdapter adapter,
QuestionDefinition calldata def,
CreateMarketParams calldata p,
uint256 initialFunding,
bytes calldata context,
VenueAuth calldata auth
)
external
payable
returns (uint256 oracleQuestionId, bytes32 conditionId, address market, bytes memory positionData)
{
if (initialFunding == 0) revert ZeroLiquidity();
{
// forge-lint: disable-next-line(asm-keccak256)
bytes32 callHash = keccak256(abi.encode(msg.sig, venueId, address(adapter), def, p, initialFunding, context));
_authorizeCreate(venueId, callHash, auth);
}
oracleQuestionId = _scheduleAndRefund(adapter, def);
CreateMarketParams memory pm = p;
pm.oracleQuestionId = oracleQuestionId;
pm.oracleAdapter = adapter;
(conditionId, market) = _createMarket(pm, msg.sender, venueId);
positionData = _seedLiquidity(conditionId, p.collateral, initialFunding, context);
uint256 sharesMinted = abi.decode(positionData, (uint256));
emit RouterAddLiquidity(conditionId, msg.sender, venueId, initialFunding, sharesMinted);
}
// ---- Legacy createMarket ABIs ---------------------------------------
//
// Pre-PRP-645 clients used a `CreateMarketParams` tuple without the
// trailing `bytes metadata` field. Adding that field changed the four
// createMarket* selectors, so pre-upgrade integrations broke.
//
// These shims re-introduce the historic selectors: they accept the
// 8-field `LegacyCreateMarketParams` tuple, stamp `metadata = ""`
// (empty bytes), and delegate to the same internal logic as the
// current entry points. The `MarketCreated` event fired is the
// current 14-arg one — legacy callers appear in indexer output
// exactly like post-upgrade markets that opted out of metadata.
//
// Venue signers that require createSig hash the same
// `(msg.sig, venueId, p, …)` bytes here as they always did (the
// legacy selector and legacy tuple encoding match the pre-PRP-645
// ABI byte-for-byte), so a pre-upgrade off-chain signer keeps
// working without changes.
struct LegacyCreateMarketParams {
uint256 oracleQuestionId;
IOracleAdapter oracleAdapter;
IERC20 collateral;
uint256 fee;
uint256 tradingStart;
uint256 tradingClose;
VoidPolicy voidPolicy;
uint16 creatorFeeBps;
}
/// @dev Widen a legacy tuple into the current `CreateMarketParams` memory
/// layout, with `metadata` left as its default empty-bytes value.
function _widen(LegacyCreateMarketParams calldata p) private pure returns (CreateMarketParams memory pm) {
pm.oracleQuestionId = p.oracleQuestionId;
pm.oracleAdapter = p.oracleAdapter;
pm.collateral = p.collateral;
pm.fee = p.fee;
pm.tradingStart = p.tradingStart;
pm.tradingClose = p.tradingClose;
pm.voidPolicy = p.voidPolicy;
pm.creatorFeeBps = p.creatorFeeBps;
// pm.metadata is empty bytes by default
}
/// @notice Legacy ABI for `createMarket`. See the current entry point
/// (with `CreateMarketParams`) for the full parameter docs.
function createMarket(uint32 venueId, LegacyCreateMarketParams calldata p, VenueAuth calldata auth)
external
returns (bytes32 conditionId, address market)
{
// forge-lint: disable-next-line(asm-keccak256)
bytes32 callHash = keccak256(abi.encode(msg.sig, venueId, p));
_authorizeCreate(venueId, callHash, auth);
return _createMarket(_widen(p), msg.sender, venueId);
}
/// @notice Legacy ABI for `createMarketAndSeed`.
function createMarketAndSeed(
uint32 venueId,
LegacyCreateMarketParams calldata p,
uint256 initialFunding,
bytes calldata context,
VenueAuth calldata auth
)
external
returns (bytes32 conditionId, address market, bytes memory positionData)
{
if (initialFunding == 0) revert ZeroLiquidity();
bytes32 callHash =
// forge-lint: disable-next-line(asm-keccak256)
keccak256(abi.encode(msg.sig, venueId, p, initialFunding, context));
_authorizeCreate(venueId, callHash, auth);
(conditionId, market) = _createMarket(_widen(p), msg.sender, venueId);
positionData = _seedLiquidity(conditionId, p.collateral, initialFunding, context);
uint256 sharesMinted = abi.decode(positionData, (uint256));
emit RouterAddLiquidity(conditionId, msg.sender, venueId, initialFunding, sharesMinted);
}
/// @notice Legacy ABI for `scheduleAndCreateMarket`.
function scheduleAndCreateMarket(
uint32 venueId,
IOracleAdapter adapter,
QuestionDefinition calldata def,
LegacyCreateMarketParams calldata p,
VenueAuth calldata auth
)
external
payable
returns (uint256 oracleQuestionId, bytes32 conditionId, address market)
{
{
// forge-lint: disable-next-line(asm-keccak256)
bytes32 callHash = keccak256(abi.encode(msg.sig, venueId, address(adapter), def, p));
_authorizeCreate(venueId, callHash, auth);
}
oracleQuestionId = _scheduleAndRefund(adapter, def);
CreateMarketParams memory pm = _widen(p);
pm.oracleQuestionId = oracleQuestionId;
pm.oracleAdapter = adapter;
(conditionId, market) = _createMarket(pm, msg.sender, venueId);
}
/// @notice Legacy ABI for `scheduleCreateAndSeed`.
function scheduleCreateAndSeed(
uint32 venueId,
IOracleAdapter adapter,
QuestionDefinition calldata def,
LegacyCreateMarketParams calldata p,
uint256 initialFunding,
bytes calldata context,
VenueAuth calldata auth
)
external
payable
returns (uint256 oracleQuestionId, bytes32 conditionId, address market, bytes memory positionData)
{
if (initialFunding == 0) revert ZeroLiquidity();
{
// forge-lint: disable-next-line(asm-keccak256)
bytes32 callHash = keccak256(abi.encode(msg.sig, venueId, address(adapter), def, p, initialFunding, context));
_authorizeCreate(venueId, callHash, auth);
}
oracleQuestionId = _scheduleAndRefund(adapter, def);
CreateMarketParams memory pm = _widen(p);
pm.oracleQuestionId = oracleQuestionId;
pm.oracleAdapter = adapter;
(conditionId, market) = _createMarket(pm, msg.sender, venueId);
positionData = _seedLiquidity(conditionId, p.collateral, initialFunding, context);
uint256 sharesMinted = abi.decode(positionData, (uint256));
emit RouterAddLiquidity(conditionId, msg.sender, venueId, initialFunding, sharesMinted);
}
/// @dev Schedule a question and refund any excess msg.value to the caller.
function _scheduleAndRefund(IOracleAdapter adapter, QuestionDefinition calldata def)
internal
returns (uint256 oracleQuestionId)
{
if (!approvedAdapters[address(adapter)]) revert InvalidAdapter();
uint256 cost = adapter.getSchedulingCost(def);
if (msg.value < cost) revert UnderpaidScheduleFee();
oracleQuestionId = adapter.scheduleQuestion{value: cost}(def);
if (msg.value > cost) {
(bool ok,) = msg.sender.call{value: msg.value - cost}("");
if (!ok) revert EthRefundFailed();
}
}
function _seedLiquidity(
bytes32 conditionId,
IERC20 collateral,
uint256 amount,
bytes calldata context
) internal returns (bytes memory positionData) {
collateral.safeTransferFrom(msg.sender, address(this), amount);
return _executeFundingAfterPull(conditionId, collateral, amount, context);
}
function _executeFundingAfterPull(
bytes32 conditionId,
IERC20 collateral,
uint256 amount,
bytes calldata context
) internal returns (bytes memory positionData) {
collateral.forceApprove(address(ORDER_ROUTER), amount);
positionData = ORDER_ROUTER.addLiquidity(conditionId, amount, context);
uint256 sharesMinted = abi.decode(positionData, (uint256));
IERC20(ORDER_ROUTER.lpToken(conditionId)).safeTransfer(msg.sender, sharesMinted);
_forwardAllOutcomes(conditionId, msg.sender);
}
/// @dev Validates the oracle question and prepares conditionId/questionIdCt in a
/// memory struct so the caller's stack frame stays within the Yul 16-slot limit.
function _buildPrep(uint256 oracleQuestionId, IOracleAdapter adapter) private returns (_MarketPrep memory s) {
if (!approvedAdapters[address(adapter)]) revert AdapterNotApproved();
s.slots = adapter.getSlotCount(oracleQuestionId);
if (s.slots < 2) revert OutcomeCountMismatch();
if (conditionIdsForOracleQuestion[oracleQuestionId].length >= MAX_MARKETS_PER_QUESTION)
revert TooManyMarketsForQuestion();
s.marketIndex = marketCountFor[oracleQuestionId]++;
s.questionIdCt = keccak256(abi.encode(oracleQuestionId, s.marketIndex));
s.conditionId = CTHelpers.getConditionId(address(this), s.questionIdCt, s.slots);
CONDITIONAL_TOKENS.prepareCondition(address(this), s.questionIdCt, s.slots);
}
function _createMarket(CreateMarketParams memory p, address creator, uint32 venueId)
internal
returns (bytes32 conditionId, address market)
{
if (address(p.collateral) == address(0)) revert ZeroAddress();
if (p.fee >= WAD) revert InvalidFee();
if (p.creatorFeeBps > MAX_CREATOR_FEE_BPS) revert FeeExceedsMax();
if (p.voidPolicy == VoidPolicy.AMM_SNAPSHOT && p.tradingClose == 0) revert InvalidTradingWindow();
if (p.tradingClose != 0 && p.tradingStart != 0 && p.tradingClose <= p.tradingStart) revert InvalidTradingWindow();
_MarketPrep memory prep = _buildPrep(p.oracleQuestionId, p.oracleAdapter);
conditionId = prep.conditionId;
market = ORDER_ROUTER.createPool(
OrderRouter.CreatePoolParams({
conditionId: prep.conditionId,
collateralToken: p.collateral,
fee: p.fee,
tradingStart: uint64(p.tradingStart),
tradingClose: uint64(p.tradingClose),
activator: creator
})
);
markets[conditionId] = MarketRecord({
oracleQuestionId: p.oracleQuestionId,
questionId: prep.questionIdCt,
outcomeSlotCount: prep.slots,
voidPolicy: p.voidPolicy,
collateralToken: p.collateral,
fee: p.fee,
_deprecatedExpectedResolutionTime: 0,
originVenueId: venueId,
oracleAdapter: p.oracleAdapter,
creator: creator,
creatorFeeBps: p.creatorFeeBps,
market: market,
tradingClose: uint64(p.tradingClose),
metadata: p.metadata
});
conditionIdsForOracleQuestion[p.oracleQuestionId].push(conditionId);
_emitCreated(conditionId, market, creator, venueId, prep.slots, prep.marketIndex, p);
}
/// @dev Emits both the legacy 13-arg and the current 14-arg
/// `MarketCreated` events. Legacy first, current second — envio's
/// dual-registered handlers see the same conditionId twice per
/// market and last-write-wins keeps `metadata` on the row. Old
/// ABI consumers pick up the legacy topic0, new consumers pick up
/// the current one.
function _emitCreated(
bytes32 conditionId,
address market,
address creator,
uint32 venueId,
uint8 slots,
uint256 marketIndex,
CreateMarketParams memory p
) internal {
emit MarketCreated(
conditionId,
market,
p.oracleQuestionId,
venueId,
creator,
address(p.collateral),
p.fee,
slots,
p.tradingStart,
p.tradingClose,
p.voidPolicy,
marketIndex,
p.creatorFeeBps
);
emit MarketCreated(
conditionId,
market,
p.oracleQuestionId,
venueId,
creator,
address(p.collateral),
p.fee,
slots,
p.tradingStart,
p.tradingClose,
p.voidPolicy,
marketIndex,
p.creatorFeeBps,
p.metadata
);
}
/// @notice Update the trading start time for a market before it opens.
/// Forwards to the CPMM; the CPMM enforces the activator check.
/// @param conditionId Target market; `msg.sender` must be its activator.
/// @param newTradingStart New unix timestamp for when trading opens; 0 = open immediately.
function setTradingStart(bytes32 conditionId, uint64 newTradingStart) external {
ORDER_ROUTER.setTradingStart(conditionId, newTradingStart, msg.sender);
}
// ---- Resolution ------------------------------------------------------
/// @notice Called by the registered oracle adapter when a question is answered.
/// Only the adapter stored in the market record for the given question
/// may call this — any other caller is rejected. If the question is not
/// managed by this router, the call is silently ignored (allows adapters
/// to forward answers for questions that have not yet been bound to a market
/// without reverting).
/// @param oracleQuestionId Oracle-level question ID the adapter is reporting on.
/// @param outcomeIdx Zero-based winning outcome index; ignored when `voided` is true.
/// @param voided True if the question was voided rather than resolved normally.
function onOracleAnswer(uint256 oracleQuestionId, uint8 outcomeIdx, bool voided) external override {
if (!approvedAdapters[msg.sender]) revert NotAuthorizedAdapter();
bytes32[] storage conditionIds = conditionIdsForOracleQuestion[oracleQuestionId];
if (conditionIds.length == 0) return; // not a router-managed question; ignore
for (uint256 i = 0; i < conditionIds.length; i++) {
_resolve(conditionIds[i], oracleQuestionId, outcomeIdx, voided);
}
}
/// @notice Pull fallback. Anyone can trigger; delegates to the adapter to
/// read the oracle state. Idempotent (CT rejects double-reports).
/// Not venue-tagged — this is a public maintenance path.
/// @param oracleQuestionId Oracle question ID to poll; must be registered with at least one market.
function pokeOracle(uint256 oracleQuestionId) external {
bytes32[] storage conditionIds = conditionIdsForOracleQuestion[oracleQuestionId];
if (conditionIds.length == 0) revert UnknownOracleQuestion();
uint8 outcomeIdx;
bool voided;
try markets[conditionIds[0]].oracleAdapter.pullAnswer(oracleQuestionId) returns (uint8 oi, bool v) {
outcomeIdx = oi;
voided = v;
} catch {
revert OracleNotAnswered();
}
for (uint256 i = 0; i < conditionIds.length; i++) {
_resolve(conditionIds[i], oracleQuestionId, outcomeIdx, voided);
}
}
function _resolve(bytes32 conditionId, uint256 oracleQuestionId, uint8 outcomeIdx, bool voided) internal {
MarketRecord storage rec = markets[conditionId];
if (CONDITIONAL_TOKENS.payoutDenominator(conditionId) != 0) return; // already resolved
uint256 slots = rec.outcomeSlotCount;
uint256[] memory payouts = new uint256[](slots);
if (!voided) {
// Slot-count mismatch: skip this market rather than blocking the whole resolution loop.
if (outcomeIdx >= slots) {
emit MarketResolutionSkipped(conditionId, outcomeIdx, uint8(slots));
return;
}
payouts[outcomeIdx] = 1;
} else if (rec.voidPolicy == VoidPolicy.UNIFORM) {
for (uint256 i = 0; i < slots; i++) payouts[i] = 1;
} else {
// AMM_SNAPSHOT: payouts proportional to 1/R_i. Only safe after trading closes —
// if trading is still open, flash loans can skew reserves. Fall back to uniform.
(,,, uint64 tradingClose_,,) = ORDER_ROUTER.poolInfo(conditionId);
if (tradingClose_ == 0 || block.timestamp < tradingClose_) {
for (uint256 i = 0; i < slots; i++) payouts[i] = 1;
} else {
uint256[] memory reserves = ORDER_ROUTER.getPoolBalances(conditionId);
uint256 scale = 1e36;
for (uint256 i = 0; i < slots; i++) {
payouts[i] = reserves[i] == 0 ? scale : scale / reserves[i];
}
}
}
// rec.questionId is the CT-level question ID: keccak256(oracleQuestionId, marketIndex).
// This is what was passed to prepareCondition, so it must be used here — not conditionId.
CONDITIONAL_TOKENS.reportPayouts(rec.questionId, payouts);
emit MarketResolved(conditionId, oracleQuestionId, outcomeIdx, voided, payouts);
}
// ---- Liquidity -------------------------------------------------------
/// @notice Deposit collateral into the market's AMM pool and receive LP shares.
/// Pass native token as `msg.value` instead of approving collateral when
/// the market uses wNative as its collateral token.
/// @param venueId Attribution only; no signature or fee on liquidity operations.
/// @param conditionId Target market.
/// @param amount Collateral to deposit; must be > 0.
/// @param context ABI-encoded `uint256[]` distribution hint for the price skew.
/// @return positionData ABI-encoded `uint256` LP shares minted.
function addLiquidity(uint32 venueId, bytes32 conditionId, uint256 amount, bytes calldata context)
external
payable
nonReentrant
returns (bytes memory positionData)
{
if (amount == 0) revert ZeroLiquidity();
MarketRecord storage rec = _requireMarket(conditionId);
_pullCollateral(rec.collateralToken, amount);
positionData = _executeFundingAfterPull(conditionId, rec.collateralToken, amount, context);
uint256 sharesMinted = abi.decode(positionData, (uint256));
emit RouterAddLiquidity(conditionId, msg.sender, venueId, amount, sharesMinted);
}
/// @notice Same as `addLiquidity` but pulls collateral via Permit2 — no prior approve() needed.
/// @param venueId Attribution only; no signature or fee on liquidity operations.
/// @param conditionId Target market.
/// @param amount Collateral to deposit; must be > 0.
/// @param context ABI-encoded `uint256[]` distribution hint for the price skew.
/// @param permit Permit2 transfer permit; `permitted.token` must match market collateral.
/// @param sig Permit2 signature authorizing the transfer.
/// @return positionData ABI-encoded `uint256` LP shares minted.
function addLiquidityWithPermit2(
uint32 venueId,
bytes32 conditionId,
uint256 amount,
bytes calldata context,
ISignatureTransfer.PermitTransferFrom calldata permit,
bytes calldata sig
) external nonReentrant returns (bytes memory positionData) {
if (amount == 0) revert ZeroLiquidity();
MarketRecord storage rec = _requireMarket(conditionId);
_pullCollateralPermit2(rec.collateralToken, amount, permit, sig);
positionData = _executeFundingAfterPull(conditionId, rec.collateralToken, amount, context);
uint256 sharesMinted = abi.decode(positionData, (uint256));
emit RouterAddLiquidity(conditionId, msg.sender, venueId, amount, sharesMinted);
}
/// @notice Burn LP shares and withdraw the corresponding share of pool collateral and outcome tokens.
/// Caller must have approved the LP token (FPMM clone ERC-20) to this router.
/// Reverts during the AMM_SNAPSHOT freeze window (after trading closes, before resolution).
/// @param venueId Attribution only.
/// @param conditionId Target market.
/// @param positionData ABI-encoded `uint256` LP shares to burn (matches `addLiquidity` return format).
function removeLiquidity(uint32 venueId, bytes32 conditionId, bytes calldata positionData) external nonReentrant {
uint256 shares = abi.decode(positionData, (uint256));
MarketRecord storage rec = _requireMarket(conditionId);
// AMM_SNAPSHOT: freeze liquidity removal between tradingClose and resolution.
if (rec.voidPolicy == VoidPolicy.AMM_SNAPSHOT
&& rec.tradingClose != 0
&& block.timestamp >= rec.tradingClose
&& CONDITIONAL_TOKENS.payoutDenominator(conditionId) == 0)
{
revert LiquidityFrozen();
}
// Transfer LP shares from user to ORDER_ROUTER; pass msg.sender so FPMM
// can settle fees atomically without relying on the ERC-20 transfer hook order.
IERC20(ORDER_ROUTER.lpToken(conditionId)).transferFrom(msg.sender, address(ORDER_ROUTER), shares);
ORDER_ROUTER.removeLiquidity(conditionId, positionData, msg.sender);
IERC20 collateral = rec.collateralToken;
// Pull both the LP's accrued fees and any fees credited to this contract
// during the share transfer; pay them out to the LP in a single transfer.
uint256 userFees = ORDER_ROUTER.withdrawFees(conditionId, msg.sender);
uint256 pmcFees = ORDER_ROUTER.withdrawFees(conditionId, address(this));
_forwardAllOutcomes(conditionId, msg.sender);
uint256 totalFees = userFees + pmcFees;
if (totalFees > 0) {
_pushCollateral(collateral, msg.sender, totalFees);
}
emit RouterRemoveLiquidity(conditionId, msg.sender, venueId, shares);
}
/// @notice Withdraw accrued LP fees for `msg.sender` from the market's AMM.
/// Collateral is routed through this contract and paid out here, so
/// the FPMM clone never transfers to a user directly.
/// @param venueId Attribution only.
/// @param conditionId Target market.
function withdrawFees(uint32 venueId, bytes32 conditionId) external nonReentrant {
MarketRecord storage rec = _requireMarket(conditionId);
uint256 paid = ORDER_ROUTER.withdrawFees(conditionId, msg.sender);
if (paid > 0) _pushCollateral(rec.collateralToken, msg.sender, paid);
emit RouterWithdrawFees(conditionId, msg.sender, venueId);
}
/// @notice Claim accrued LP fees across many markets in a single call. The
/// router pulls and aggregates the fees per collateral token; this
/// contract pays them out — one transfer per token, collapsing many
/// fee payouts into a single event per token. The caller supplies the
/// markets (the indexer surfaces a wallet's LP markets); no global
/// registry is required. Mechanism knowledge stays in the router.
/// @param venueId Attribution only.
/// @param conditionIds Markets to claim from; must be non-empty.
function claimFees(uint32 venueId, bytes32[] calldata conditionIds) external nonReentrant {
if (conditionIds.length == 0) revert ZeroLiquidity();
_settleFeeClaim(venueId, conditionIds, msg.sender);
}
/// @notice Claim accrued LP fees on behalf of `owner` across many markets,
/// authorized by an EIP-712 signature from `owner`. The collateral is
/// always paid to `owner`, never the caller — so a relayer can submit
/// the tx but cannot force or redirect a payout. Without this gate any
/// third party could trigger payouts and manufacture taxable events
/// for the owner; the signature ensures only the owner (directly via
/// `claimFees`) or an explicitly authorized claim can move their fees.
/// @param owner LP whose fees are claimed; receives the collateral.
/// @param nonce Unique value preventing replay; scoped per `owner`.
/// @param deadline Unix timestamp after which the authorization expires.
/// @param sig EIP-712 signature from `owner` over the ClaimFeesAuthorization struct.
/// @param venueId Attribution only.
/// @param conditionIds Markets to claim from; must be non-empty.
function claimFeesFor(
address owner,
uint256 nonce,
uint256 deadline,
bytes calldata sig,
uint32 venueId,
bytes32[] calldata conditionIds
) external nonReentrant {
if (conditionIds.length == 0) revert ZeroLiquidity();
if (block.timestamp > deadline) revert ClaimFeesAuthExpired();
if (claimFeesNonceUsed[owner][nonce]) revert ClaimFeesNonceUsed();
claimFeesNonceUsed[owner][nonce] = true;
bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
CLAIM_FEES_AUTH_TYPEHASH,
owner,
venueId,
keccak256(abi.encodePacked(conditionIds)),
nonce,
deadline
)));
if (!SignatureChecker.isValidSignatureNow(owner, digest, sig)) revert ClaimFeesSignatureInvalid();
_settleFeeClaim(venueId, conditionIds, owner);
}
/// @dev Pull each market's accrued fees for `account` via the router (which
/// aggregates per collateral token), then pay `account` once per token.
function _settleFeeClaim(uint32 venueId, bytes32[] calldata conditionIds, address account) internal {
(IERC20[] memory tokens, uint256[] memory amounts) =
ORDER_ROUTER.withdrawFeesMany(conditionIds, account);
for (uint256 i = 0; i < conditionIds.length; i++) {
emit RouterWithdrawFees(conditionIds[i], account, venueId);
}
for (uint256 k = 0; k < tokens.length; k++) {
if (amounts[k] > 0) _pushCollateral(tokens[k], account, amounts[k]);
}
}
// ---- Trading ---------------------------------------------------------
/// @dev Pull `amount` of `collateral` from msg.sender into this contract.
/// If msg.value > 0 the sender is paying native: wrap it via wNative.
/// The market must use wNative as collateral, and msg.value must equal amount exactly.
function _pullCollateral(IERC20 collateral, uint256 amount) internal {
if (msg.value > 0) {
if (address(collateral) != address(wNative)) revert NativeNotSupported();
if (msg.value != amount) revert NativeAmountMismatch();
wNative.deposit{value: msg.value}();
} else {
collateral.safeTransferFrom(msg.sender, address(this), amount);
}
}
/// @dev Same as _pullCollateral but pulls via Permit2 instead of approve+transferFrom.
function _pullCollateralPermit2(
IERC20 collateral,
uint256 amount,
ISignatureTransfer.PermitTransferFrom calldata permit,
bytes calldata sig
) internal {
if (PERMIT2 == address(0)) revert Permit2NotConfigured();
// Verify token matches market collateral BEFORE the transfer.
if (permit.permitted.token != address(collateral)) revert InvalidPermitToken();
ISignatureTransfer(PERMIT2).permitTransferFrom(
permit,
ISignatureTransfer.SignatureTransferDetails({to: address(this), requestedAmount: amount}),
msg.sender,
sig
);
}
/// @dev Send `amount` of `collateral` to `to`.
/// If the market collateral is wNative, unwrap first and send native.
/// If the native push fails (e.g. recipient is a contract that rejects ETH),
/// fall back to re-wrapping and sending as wNative ERC-20.
function _pushCollateral(IERC20 collateral, address to, uint256 amount) internal {
if (address(wNative) != address(0) && address(collateral) == address(wNative)) {
wNative.withdraw(amount);
(bool ok,) = payable(to).call{value: amount}("");
if (!ok) {
wNative.deposit{value: amount}();
IERC20(address(wNative)).safeTransfer(to, amount);
}
} else {
collateral.safeTransfer(to, amount);
}
}
/// @dev Bundles the post-trade settlement state for `buy`. Same rationale
/// as `SellSettlement` — packing into a memory struct lets the legacy
/// codegen avoid 8+ simultaneous stack slots when emitting `RouterBuy`.
struct BuySettlement {
bytes32 conditionId;
uint32 venueId;
uint256 indexSet;
uint256 investmentAmount;
uint256 outcomeTokensBought;
uint256 venueFee;
uint256 marketFee;
uint256 creatorFee;
uint256 toCpmm;
uint256 feeRate;
}
/// @notice Buy outcome tokens. `investmentAmount` is what the user pays in collateral;
/// `maxFeeBps` caps the combined LP + venue + creator fee in basis points.
/// @param venueId Routing venue for fee attribution and signature gate.
/// @param conditionId Target market.
/// @param indexSet Bitmask of outcome slots to buy (bit 0 = outcome 0).
/// @param investmentAmount Collateral the user spends (covers all fees); must be > 0.
/// @param minOutcomeTokensToBuy Slippage guard; reverts if fewer tokens would be received.
/// @param maxFeeBps Revert if total fees (LP + venue + creator) exceed this in bps.
/// @param auth Venue authorization; only checked when venue has `requiresTradeSig`.
/// @return outcomeTokensBought Outcome tokens credited to `msg.sender`.
function buy(
uint32 venueId,
bytes32 conditionId,
uint256 indexSet,
uint256 investmentAmount,
uint256 minOutcomeTokensToBuy,
uint256 maxFeeBps,
VenueAuth calldata auth
) external payable nonReentrant returns (uint256 outcomeTokensBought) {
if (investmentAmount == 0) revert ZeroLiquidity();
if (indexSet == 0) revert InvalidOutcomeIndex();
BuySettlement memory s;
s.conditionId = conditionId;
s.venueId = venueId;
s.indexSet = indexSet;
s.investmentAmount = investmentAmount;
{
TradeAuth memory ta;
{
// forge-lint: disable-next-line(asm-keccak256)
bytes32 callHash = keccak256(abi.encode(this.buy.selector, venueId, conditionId, indexSet, investmentAmount, minOutcomeTokensToBuy, maxFeeBps));
ta = _authorizeTrade(venueId, conditionId, callHash, auth);
}
MarketRecord storage rec = _requireMarket(conditionId);
s.feeRate = rec.fee;
if ((s.feeRate * BPS_DENOMINATOR) / WAD + ta.routingFeeBps + ta.marketFeeBps + rec.creatorFeeBps > maxFeeBps) revert FeeExceedsMax();
s.venueFee = (investmentAmount * ta.routingFeeBps) / BPS_DENOMINATOR;
s.marketFee = (investmentAmount * ta.marketFeeBps) / BPS_DENOMINATOR;
s.creatorFee = (investmentAmount * rec.creatorFeeBps) / BPS_DENOMINATOR;
s.toCpmm = investmentAmount - s.venueFee - s.marketFee - s.creatorFee;
IERC20 collateral = rec.collateralToken;
_pullCollateral(collateral, investmentAmount);
if (s.venueFee > 0) collateral.safeTransfer(ta.routingFeeRecipient, s.venueFee);
if (s.marketFee > 0) collateral.safeTransfer(ta.marketFeeRecipient, s.marketFee);
if (s.creatorFee > 0) collateral.safeTransfer(rec.creator, s.creatorFee);
collateral.forceApprove(address(ORDER_ROUTER), s.toCpmm);
}
outcomeTokensBought = ORDER_ROUTER.buy(conditionId, s.toCpmm, indexSet, minOutcomeTokensToBuy);
s.outcomeTokensBought = outcomeTokensBought;
_forwardBoughtTokens(conditionId, indexSet, outcomeTokensBought);
_emitBuy(s);
}
/// @dev Final event emit for `buy`. Extracted so the 8-arg `RouterBuy` doesn't
/// have to be assembled in the caller's stack frame.
function _emitBuy(BuySettlement memory s) internal {
uint256 lpFee = (s.toCpmm * s.feeRate) / WAD;
emit RouterBuy(
s.conditionId,
msg.sender,
s.venueId,
s.indexSet,
s.investmentAmount,
s.outcomeTokensBought,
lpFee,
s.venueFee,
s.marketFee,
s.creatorFee
);
}
/// @notice Same as `buy` but pulls collateral via Permit2 — no prior approve() needed.
/// @param venueId Routing venue for fee attribution and signature gate.
/// @param conditionId Target market.
/// @param indexSet Bitmask of outcome slots to buy (bit 0 = outcome 0).
/// @param investmentAmount Collateral the user spends; must be > 0.
/// @param minOutcomeTokensToBuy Slippage guard.
/// @param maxFeeBps Total fee cap in bps.
/// @param auth Venue authorization.
/// @param permit Permit2 transfer permit; `permitted.token` must match market collateral.
/// @param sig Permit2 signature authorizing the transfer.
/// @return outcomeTokensBought Outcome tokens credited to `msg.sender`.
function buyWithPermit2(
uint32 venueId,
bytes32 conditionId,
uint256 indexSet,
uint256 investmentAmount,
uint256 minOutcomeTokensToBuy,
uint256 maxFeeBps,
VenueAuth calldata auth,
ISignatureTransfer.PermitTransferFrom calldata permit,
bytes calldata sig
) external nonReentrant returns (uint256 outcomeTokensBought) {
if (investmentAmount == 0) revert ZeroLiquidity();
if (indexSet == 0) revert InvalidOutcomeIndex();
BuySettlement memory s;
s.conditionId = conditionId;
s.venueId = venueId;
s.indexSet = indexSet;
s.investmentAmount = investmentAmount;
{
TradeAuth memory ta;
{
// forge-lint: disable-next-line(asm-keccak256)
bytes32 callHash = keccak256(abi.encode(this.buyWithPermit2.selector, venueId, conditionId, indexSet, investmentAmount, minOutcomeTokensToBuy, maxFeeBps));
ta = _authorizeTrade(venueId, conditionId, callHash, auth);
}
MarketRecord storage rec = _requireMarket(conditionId);
s.feeRate = rec.fee;
if ((s.feeRate * BPS_DENOMINATOR) / WAD + ta.routingFeeBps + ta.marketFeeBps + rec.creatorFeeBps > maxFeeBps) revert FeeExceedsMax();
s.venueFee = (investmentAmount * ta.routingFeeBps) / BPS_DENOMINATOR;
s.marketFee = (investmentAmount * ta.marketFeeBps) / BPS_DENOMINATOR;
s.creatorFee = (investmentAmount * rec.creatorFeeBps) / BPS_DENOMINATOR;
s.toCpmm = investmentAmount - s.venueFee - s.marketFee - s.creatorFee;
IERC20 collateral = rec.collateralToken;
if (permit.permitted.token != address(collateral)) revert InvalidPermitToken();
_pullCollateralPermit2(collateral, investmentAmount, permit, sig);
if (s.venueFee > 0) collateral.safeTransfer(ta.routingFeeRecipient, s.venueFee);
if (s.marketFee > 0) collateral.safeTransfer(ta.marketFeeRecipient, s.marketFee);
if (s.creatorFee > 0) collateral.safeTransfer(rec.creator, s.creatorFee);
collateral.forceApprove(address(ORDER_ROUTER), s.toCpmm);
}
outcomeTokensBought = ORDER_ROUTER.buy(conditionId, s.toCpmm, indexSet, minOutcomeTokensToBuy);
s.outcomeTokensBought = outcomeTokensBought;
_forwardBoughtTokens(conditionId, indexSet, outcomeTokensBought);
_emitBuy(s);
}
/// @dev Bundles the post-trade settlement state for `sell`. Building this
/// struct progressively lets the legacy codegen (used by `forge coverage`)
/// pop intermediate locals before the event emit — emitting `RouterSell`
/// with 9 inline args overflows the 16-slot stack under instrumentation.
struct SellSettlement {
bytes32 conditionId;
uint32 venueId;
uint256 outcomeIndex;
uint256 returnAmount;
uint256 outcomeTokensSold;
uint256 venueFee;
uint256 marketFee;
uint256 creatorFee;
uint256 amountToTrader;
uint256 feeRate;
address feeRecipient;
address marketFeeRecipient;
address creatorAddr;
IERC20 collateral;
}
/// @notice Sell outcome tokens. `returnAmount` is the collateral the CPMM returns to the
/// router; the user receives `returnAmount` minus all fees. Caller must hold the
/// outcome tokens and have set ERC-1155 approval for this router.
/// @param venueId Routing venue for fee attribution and signature gate.
/// @param conditionId Target market.
/// @param outcomeIndex Zero-based index of the outcome slot being sold.
/// @param returnAmount Desired collateral out (before fees); must be > 0.
/// @param maxOutcomeTokensToSell Slippage guard; reverts if more tokens would be required.
/// @param maxFeeBps Total fee cap in bps.
/// @param auth Venue authorization; only checked when venue has `requiresTradeSig`.
/// @return outcomeTokensSold Outcome tokens deducted from `msg.sender`.
function sell(
uint32 venueId,
bytes32 conditionId,
uint256 outcomeIndex,
uint256 returnAmount,
uint256 maxOutcomeTokensToSell,
uint256 maxFeeBps,
VenueAuth calldata auth
) external nonReentrant returns (uint256 outcomeTokensSold) {
if (returnAmount == 0) revert ZeroLiquidity();
SellSettlement memory s;
s.conditionId = conditionId;
s.venueId = venueId;
s.outcomeIndex = outcomeIndex;
s.returnAmount = returnAmount;
TradeAuth memory ta;
{
// forge-lint: disable-next-line(asm-keccak256)
bytes32 callHash = keccak256(abi.encode(this.sell.selector, venueId, conditionId, outcomeIndex, returnAmount, maxOutcomeTokensToSell, maxFeeBps));
ta = _authorizeTrade(venueId, conditionId, callHash, auth);
}
MarketRecord storage rec = _requireMarket(conditionId);
s.feeRate = rec.fee;
// Normalize LP fee component to /WAD (same base as buy) for a consistent maxFeeBps check.
if ((s.feeRate * BPS_DENOMINATOR) / WAD + ta.routingFeeBps + ta.marketFeeBps + rec.creatorFeeBps > maxFeeBps) revert FeeExceedsMax();
s.venueFee = (returnAmount * ta.routingFeeBps) / BPS_DENOMINATOR;
s.marketFee = (returnAmount * ta.marketFeeBps) / BPS_DENOMINATOR;
s.creatorFee = (returnAmount * rec.creatorFeeBps) / BPS_DENOMINATOR;
outcomeTokensSold = ORDER_ROUTER.calcSellAmount(conditionId, returnAmount, outcomeIndex);
if (outcomeTokensSold > maxOutcomeTokensToSell) revert MaxAmountExceeded();
s.outcomeTokensSold = outcomeTokensSold;
IERC1155(address(CONDITIONAL_TOKENS)).safeTransferFrom(
msg.sender, address(this), ORDER_ROUTER.positionIds(conditionId)[outcomeIndex], outcomeTokensSold, ""
);
ORDER_ROUTER.sell(conditionId, returnAmount, outcomeIndex, outcomeTokensSold);
s.collateral = rec.collateralToken;
s.feeRecipient = ta.routingFeeRecipient;
s.marketFeeRecipient = ta.marketFeeRecipient;
s.creatorAddr = rec.creator;
s.amountToTrader = returnAmount - s.venueFee - s.marketFee - s.creatorFee;
_settleSell(s);
}
/// @dev Post-trade settlement + event emit for `sell`. Extracted so the
/// 9-arg `RouterSell` event doesn't have to be assembled in the caller's
/// stack frame.
function _settleSell(SellSettlement memory s) internal {
if (s.venueFee > 0) s.collateral.safeTransfer(s.feeRecipient, s.venueFee);
if (s.marketFee > 0) s.collateral.safeTransfer(s.marketFeeRecipient, s.marketFee);
if (s.creatorFee > 0) s.collateral.safeTransfer(s.creatorAddr, s.creatorFee);
_pushCollateral(s.collateral, msg.sender, s.amountToTrader);
uint256 lpFee = (s.returnAmount * s.feeRate) / (WAD - s.feeRate);
emit RouterSell(
s.conditionId,
msg.sender,
s.venueId,
s.outcomeIndex,
s.returnAmount,
s.amountToTrader,
s.outcomeTokensSold,
lpFee,
s.venueFee,
s.marketFee,
s.creatorFee
);
}
/// @notice Quote how many outcome tokens `investmentAmount` collateral would buy from the FPMM.
/// Does not account for venue or creator fees — caller should subtract those first.
/// Use quoteBuyFull for an accurate end-to-end quote including all fees.
/// @param conditionId Target market.
/// @param indexSet Outcome bitmask to price.
/// @param investmentAmount Collateral in (net of fees).
/// @return Outcome tokens that would be received.
function quoteBuy(bytes32 conditionId, uint256 indexSet, uint256 investmentAmount)
external
view
returns (uint256)
{
return ORDER_ROUTER.calcBuyAmount(conditionId, investmentAmount, indexSet);
}
/// @notice Full quote for buy: accounts for LP fee, routing venue fee, market-attribution fee,
/// and creator fee. Pass the gross `investmentAmount` you intend to call buy() with.
/// @param conditionId Target market.
/// @param indexSet Outcome bitmask to price.
/// @param investmentAmount Gross collateral the caller will spend (same value passed to buy).
/// @param routingVenueId Venue the caller will route through (same value passed to buy); 0 = none.
/// @return Outcome tokens that would be received after all fees.
function quoteBuyFull(
bytes32 conditionId,
uint256 indexSet,
uint256 investmentAmount,
uint32 routingVenueId
) external view returns (uint256) {
MarketRecord storage rec = markets[conditionId];
uint256 toCpmm = investmentAmount;
toCpmm -= (investmentAmount * rec.creatorFeeBps) / BPS_DENOMINATOR;
(, uint16 marketFeeBps,) = VENUE_REGISTRY.marketFeeInfoFull(rec.originVenueId);
toCpmm -= (investmentAmount * marketFeeBps) / BPS_DENOMINATOR;
if (routingVenueId != 0) {
(,, uint16 venueFeeBps,,,) = VENUE_REGISTRY.venueForRoutingFull(routingVenueId);
toCpmm -= (investmentAmount * venueFeeBps) / BPS_DENOMINATOR;
}
return ORDER_ROUTER.calcBuyAmount(conditionId, toCpmm, indexSet);
}
/// @notice Quote how many outcome tokens must be sold to receive `returnAmount` collateral from the FPMM.
/// Does not account for venue or creator fees — those are deducted from `returnAmount` after the sell.
/// @param conditionId Target market.
/// @param outcomeIndex Zero-based slot index being sold.
/// @param returnAmount Desired collateral out (before fees).
/// @return Outcome tokens that must be provided to the FPMM.
function quoteSell(bytes32 conditionId, uint256 outcomeIndex, uint256 returnAmount)
external
view
returns (uint256)
{
return ORDER_ROUTER.calcSellAmount(conditionId, returnAmount, outcomeIndex);
}
// ---- Complete sets ---------------------------------------------------
/// @notice Mint a complete set of outcome tokens for `amount` collateral.
/// User pays `amount` collateral and receives `amount` of every
/// outcome token. No AMM, no fee — the 1:1 arbitrage primitive.
/// @param venueId Attribution only; no signature required, no fee skim.
/// @param conditionId The market's condition id.
/// @param amount Quantity of each outcome token to mint.
function mintCompleteSet(uint32 venueId, bytes32 conditionId, uint256 amount) external payable nonReentrant {
if (amount == 0) revert ZeroLiquidity();
MarketRecord storage rec = _requireMarket(conditionId);
IERC20 collateral = rec.collateralToken;
uint256 slots = rec.outcomeSlotCount;
_pullCollateral(collateral, amount);
collateral.forceApprove(address(CONDITIONAL_TOKENS), amount);
CONDITIONAL_TOKENS.splitPosition(
collateral, bytes32(0), conditionId, CTHelpers.buildSlotPartition(slots), amount
);
uint256[] memory ids = ORDER_ROUTER.positionIds(conditionId);
uint256[] memory amounts = new uint256[](slots);
for (uint256 i = 0; i < slots; i++) amounts[i] = amount;
IERC1155(address(CONDITIONAL_TOKENS)).safeBatchTransferFrom(address(this), msg.sender, ids, amounts, "");
emit RouterMintCompleteSet(conditionId, msg.sender, venueId, amount);
}
/// @notice Burn a complete set of outcome tokens and receive `amount` collateral.
/// Inverse of `mintCompleteSet`. User must hold `amount` of every
/// outcome token and have set ERC-1155 approval for the router.
/// @param venueId Attribution only; no signature required, no fee skim.
/// @param conditionId The market's condition id.
/// @param amount Quantity of each outcome token to burn.
function mergeCompleteSet(uint32 venueId, bytes32 conditionId, uint256 amount) external nonReentrant {
if (amount == 0) revert ZeroLiquidity();
MarketRecord storage rec = _requireMarket(conditionId);
IERC20 collateral = rec.collateralToken;
uint256 slots = rec.outcomeSlotCount;
uint256[] memory ids = ORDER_ROUTER.positionIds(conditionId);
uint256[] memory amounts = new uint256[](slots);
for (uint256 i = 0; i < slots; i++) amounts[i] = amount;
IERC1155(address(CONDITIONAL_TOKENS)).safeBatchTransferFrom(msg.sender, address(this), ids, amounts, "");
CONDITIONAL_TOKENS.mergePositions(
collateral, bytes32(0), conditionId, CTHelpers.buildSlotPartition(slots), amount
);
_pushCollateral(collateral, msg.sender, amount);
emit RouterMergeCompleteSet(conditionId, msg.sender, venueId, amount);
}
// ---- Redemption ------------------------------------------------------
/// @notice Redeem winning outcome tokens for collateral after market resolution.
/// Transfers all held tokens for each `indexSet` from `msg.sender` and returns
/// the proportional collateral according to ConditionalTokens payout numerators.
/// @param venueId Attribution only; no fee on redemption.
/// @param conditionId Resolved market to redeem from.
/// @param indexSets Array of outcome bitmasks to redeem; must be non-empty.
function redeem(uint32 venueId, bytes32 conditionId, uint256[] calldata indexSets) external nonReentrant {
if (indexSets.length == 0) revert ZeroLiquidity();
MarketRecord storage rec = _requireMarket(conditionId);
IERC20 collateral = rec.collateralToken;
uint256 n = indexSets.length;
uint256[] memory ids = new uint256[](n);
address[] memory froms = new address[](n);
for (uint256 i = 0; i < n; i++) {
ids[i] = CTHelpers.getPositionId(
collateral, CTHelpers.getCollectionId(bytes32(0), conditionId, indexSets[i])
);
froms[i] = msg.sender;
}
uint256[] memory balances = IERC1155(address(CONDITIONAL_TOKENS)).balanceOfBatch(froms, ids);
IERC1155(address(CONDITIONAL_TOKENS)).safeBatchTransferFrom(msg.sender, address(this), ids, balances, "");
uint256 collateralBefore = collateral.balanceOf(address(this));
CONDITIONAL_TOKENS.redeemPositions(collateral, bytes32(0), conditionId, indexSets);
uint256 collateralDelta = collateral.balanceOf(address(this)) - collateralBefore;
if (collateralDelta > 0) {
_pushCollateral(collateral, msg.sender, collateralDelta);
}
emit RouterRedeem(conditionId, msg.sender, venueId);
}
/// @notice Redeem outcome tokens on behalf of `owner` via an EIP-712 signed
/// authorization. Collateral is always sent to `owner`, not the caller.
///
/// Prerequisite: `owner` must call
/// `CONDITIONAL_TOKENS.setApprovalForAll(address(this), true)` once.
/// @param owner Token holder whose positions are being redeemed; receives the collateral.
/// @param nonce Unique value preventing replay; scoped per `owner`.
/// @param deadline Unix timestamp after which the authorization expires.
/// @param sig EIP-712 signature from `owner` over the RedeemAuthorization struct.
/// @param venueId Attribution only.
/// @param conditionId Resolved market to redeem from.
/// @param indexSets Array of outcome bitmasks to redeem.
function redeemFor(
address owner,
uint256 nonce,
uint256 deadline,
bytes calldata sig,
uint32 venueId,
bytes32 conditionId,
uint256[] calldata indexSets
) external nonReentrant {
if (block.timestamp > deadline) revert RedeemAuthExpired();
if (redeemNonceUsed[owner][nonce]) revert RedeemNonceUsed();
redeemNonceUsed[owner][nonce] = true;
bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
REDEEM_AUTH_TYPEHASH,
owner,
venueId,
conditionId,
keccak256(abi.encodePacked(indexSets)),
nonce,
deadline
)));
if (!SignatureChecker.isValidSignatureNow(owner, digest, sig)) revert RedeemSignatureInvalid();
MarketRecord storage rec = _requireMarket(conditionId);
IERC20 collateral = rec.collateralToken;
uint256 n = indexSets.length;
uint256[] memory ids = new uint256[](n);
address[] memory froms = new address[](n);
for (uint256 i = 0; i < n; i++) {
ids[i] = CTHelpers.getPositionId(
collateral, CTHelpers.getCollectionId(bytes32(0), conditionId, indexSets[i])
);
froms[i] = owner;
}
uint256[] memory balances = IERC1155(address(CONDITIONAL_TOKENS)).balanceOfBatch(froms, ids);
IERC1155(address(CONDITIONAL_TOKENS)).safeBatchTransferFrom(owner, address(this), ids, balances, "");
uint256 collateralBefore = collateral.balanceOf(address(this));
CONDITIONAL_TOKENS.redeemPositions(collateral, bytes32(0), conditionId, indexSets);
uint256 collateralDelta = collateral.balanceOf(address(this)) - collateralBefore;
if (collateralDelta > 0) {
_pushCollateral(collateral, owner, collateralDelta);
}
emit RouterRedeem(conditionId, owner, venueId);
}
// ---- Internal --------------------------------------------------------
/// @dev Transfer `amount` of each outcome in `indexSet` from this contract
/// to msg.sender. Called after ORDER_ROUTER.buy deposits the tokens here.
function _forwardBoughtTokens(bytes32 conditionId, uint256 indexSet, uint256 amount) internal {
uint256[] memory ids = ORDER_ROUTER.positionIds(conditionId);
uint256 n = ids.length;
uint256 bits;
for (uint256 i = 0; i < n; i++) { if (indexSet >> i & 1 != 0) bits++; }
if (bits == 1) {
uint256 k; while ((indexSet >> k) & 1 == 0) k++;
IERC1155(address(CONDITIONAL_TOKENS)).safeTransferFrom(address(this), msg.sender, ids[k], amount, "");
} else {
uint256[] memory outIds = new uint256[](bits);
uint256[] memory amounts = new uint256[](bits);
uint256 j;
for (uint256 i = 0; i < n; i++) {
if (indexSet >> i & 1 != 0) { outIds[j] = ids[i]; amounts[j] = amount; j++; }
}
IERC1155(address(CONDITIONAL_TOKENS)).safeBatchTransferFrom(address(this), msg.sender, outIds, amounts, "");
}
}
/// @dev Load the market record and assert the market exists. Returns the
/// storage pointer so callers can read its fields without a second
/// SLOAD.
function _requireMarket(bytes32 conditionId) internal view returns (MarketRecord storage rec) {
rec = markets[conditionId];
if (rec.outcomeSlotCount == 0) revert UnknownMarket();
}
function _forwardAllOutcomes(bytes32 conditionId, address to) internal {
uint256[] memory ids = ORDER_ROUTER.positionIds(conditionId);
uint256 n = ids.length;
address[] memory addrs = new address[](n);
for (uint256 i = 0; i < n; i++) addrs[i] = address(this);
uint256[] memory balances = IERC1155(address(CONDITIONAL_TOKENS)).balanceOfBatch(addrs, ids);
bool any;
for (uint256 i = 0; i < n; i++) {
if (balances[i] > 0) {
any = true;
break;
}
}
if (any) {
IERC1155(address(CONDITIONAL_TOKENS)).safeBatchTransferFrom(address(this), to, ids, balances, "");
}
}
}
Other files
src/types/OracleTypes.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; /// @notice Minimal stubs for the ProphecyOracle's external types. Matches the /// oracle's OracleTypes.sol exactly so ABI encoding is compatible. enum AnswerType { NumericAnswer, DiscreteAnswer } /// @notice Inclusive numeric range. `low <= aggregatedValue <= high` matches the bucket. struct Interval { int256 low; int256 high; } struct ValidAnswers { AnswerType answerType; string[] discreteOutcomes; Interval[] numericIntervals; uint64 numericDecimals; } enum QuestionSourceType { Website, JSON, Contract } struct QuestionSource { QuestionSourceType sourceType; bytes params; } enum QuestionStatus { None, Scheduled, AwaitingAnswer, Resolved, Voided } struct QuestionDefinition { string questionText; QuestionSource[] sources; ValidAnswers validAnswers; uint256 resolutionTime; uint256 minAgreement; uint256 subcommitteeSize; uint256 subcommitteeThreshold; } struct Answer { uint64 timestamp; bool voided; uint8 outcomeIdx; int256 numericValue; uint256[] receiptIds; } struct Question { address creator; AnswerType answerType; string[] discreteOutcomes; Interval[] numericIntervals; uint64 numericDecimals; uint256[] sourceIds; uint256 asyncSourceCount; uint256 resolutionTime; uint256 minAgreement; uint256 subcommitteeSize; uint256 subcommitteeThreshold; QuestionStatus status; bool answerPosted; bool voided; string questionText; }lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.20; /** * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822Proxiable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); }lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.20; import {IERC165} from "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC-1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[ERC]. */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the value of tokens of token type `id` owned by `account`. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] calldata accounts, uint256[] calldata ids ) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the zero address. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`. * * WARNING: This function can potentially allow a reentrancy attack when transferring tokens * to an untrusted contract, when invoking {onERC1155Received} on the receiver. * Ensure to follow the checks-effects-interactions pattern and consider employing * reentrancy guards when interacting with untrusted contracts. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `value` amount. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * WARNING: This function can potentially allow a reentrancy attack when transferring tokens * to an untrusted contract, when invoking {onERC1155BatchReceived} on the receiver. * Ensure to follow the checks-effects-interactions pattern and consider employing * reentrancy guards when interacting with untrusted contracts. * * Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments. * * Requirements: * * - `ids` and `values` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; }lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol) pragma solidity ^0.8.20; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at, * consider using {ReentrancyGuardTransient} instead. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = 2; /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard struct ReentrancyGuardStorage { uint256 _status; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00; function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) { assembly { $.slot := ReentrancyGuardStorageLocation } } /** * @dev Unauthorized reentrant call. */ error ReentrancyGuardReentrantCall(); function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); $._status = NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { _nonReentrantBefore(); _; _nonReentrantAfter(); } function _nonReentrantBefore() private { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); // On the first call to nonReentrant, _status will be NOT_ENTERED if ($._status == ENTERED) { revert ReentrancyGuardReentrantCall(); } // Any calls to nonReentrant after this point will fail $._status = ENTERED; } function _nonReentrantAfter() private { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) $._status = NOT_ENTERED; } /** * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a * `nonReentrant` function in the call stack. */ function _reentrancyGuardEntered() internal view returns (bool) { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); return $._status == ENTERED; } }lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol) pragma solidity ^0.8.20; import {Panic} from "../Panic.sol"; import {SafeCast} from "./SafeCast.sol"; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Floor, // Toward negative infinity Ceil, // Toward positive infinity Trunc, // Toward zero Expand // Away from zero } /** * @dev Returns the addition of two unsigned integers, with an success flag (no overflow). */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow). */ function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow). */ function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a success flag (no division by zero). */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero). */ function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant. * * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone. * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute * one branch when needed, making this function more expensive. */ function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) { unchecked { // branchless ternary works because: // b ^ (a ^ b) == a // b ^ 0 == b return b ^ ((a ^ b) * SafeCast.toUint(condition)); } } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return ternary(a > b, a, b); } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return ternary(a < b, a, b); } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds towards infinity instead * of rounding towards zero. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { // Guarantee the same behavior as in a regular Solidity division. Panic.panic(Panic.DIVISION_BY_ZERO); } // The following calculation ensures accurate ceiling division without overflow. // Since a is non-zero, (a - 1) / b will not overflow. // The largest possible result occurs when (a - 1) / b is type(uint256).max, // but the largest value we can obtain is type(uint256).max - 1, which happens // when a = type(uint256).max and b = 1. unchecked { return SafeCast.toUint(a > 0) * ((a - 1) / b + 1); } } /** * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or * denominator == 0. * * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by * Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2²⁵⁶ + prod0. uint256 prod0 = x * y; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0. if (denominator <= prod1) { Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW)); } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. // Always >= 1. See https://cs.stackexchange.com/q/138556/92363. uint256 twos = denominator & (0 - denominator); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv ≡ 1 mod 2⁴. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also // works in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2⁸ inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶ inverse *= 2 - denominator * inverse; // inverse mod 2³² inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴ inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸ inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶ // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @dev Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0); } /** * @dev Calculate the modular multiplicative inverse of a number in Z/nZ. * * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0. * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible. * * If the input value is not inversible, 0 is returned. * * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}. */ function invMod(uint256 a, uint256 n) internal pure returns (uint256) { unchecked { if (n == 0) return 0; // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version) // Used to compute integers x and y such that: ax + ny = gcd(a, n). // When the gcd is 1, then the inverse of a modulo n exists and it's x. // ax + ny = 1 // ax = 1 + (-y)n // ax ≡ 1 (mod n) # x is the inverse of a modulo n // If the remainder is 0 the gcd is n right away. uint256 remainder = a % n; uint256 gcd = n; // Therefore the initial coefficients are: // ax + ny = gcd(a, n) = n // 0a + 1n = n int256 x = 0; int256 y = 1; while (remainder != 0) { uint256 quotient = gcd / remainder; (gcd, remainder) = ( // The old remainder is the next gcd to try. remainder, // Compute the next remainder. // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd // where gcd is at most n (capped to type(uint256).max) gcd - remainder * quotient ); (x, y) = ( // Increment the coefficient of a. y, // Decrement the coefficient of n. // Can overflow, but the result is casted to uint256 so that the // next value of y is "wrapped around" to a value between 0 and n - 1. x - y * int256(quotient) ); } if (gcd != 1) return 0; // No inverse exists. return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative. } } /** * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`. * * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that * `a**(p-2)` is the modular multiplicative inverse of a in Fp. * * NOTE: this function does NOT check that `p` is a prime greater than `2`. */ function invModPrime(uint256 a, uint256 p) internal view returns (uint256) { unchecked { return Math.modExp(a, p - 2, p); } } /** * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m) * * Requirements: * - modulus can't be zero * - underlying staticcall to precompile must succeed * * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make * sure the chain you're using it on supports the precompiled contract for modular exponentiation * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, * the underlying function will succeed given the lack of a revert, but the result may be incorrectly * interpreted as 0. */ function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) { (bool success, uint256 result) = tryModExp(b, e, m); if (!success) { Panic.panic(Panic.DIVISION_BY_ZERO); } return result; } /** * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m). * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying * to operate modulo 0 or if the underlying precompile reverted. * * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack * of a revert, but the result may be incorrectly interpreted as 0. */ function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) { if (m == 0) return (false, 0); assembly ("memory-safe") { let ptr := mload(0x40) // | Offset | Content | Content (Hex) | // |-----------|------------|--------------------------------------------------------------------| // | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 | // | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 | // | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 | // | 0x60:0x7f | value of b | 0x<.............................................................b> | // | 0x80:0x9f | value of e | 0x<.............................................................e> | // | 0xa0:0xbf | value of m | 0x<.............................................................m> | mstore(ptr, 0x20) mstore(add(ptr, 0x20), 0x20) mstore(add(ptr, 0x40), 0x20) mstore(add(ptr, 0x60), b) mstore(add(ptr, 0x80), e) mstore(add(ptr, 0xa0), m) // Given the result < m, it's guaranteed to fit in 32 bytes, // so we can use the memory scratch space located at offset 0. success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20) result := mload(0x00) } } /** * @dev Variant of {modExp} that supports inputs of arbitrary length. */ function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) { (bool success, bytes memory result) = tryModExp(b, e, m); if (!success) { Panic.panic(Panic.DIVISION_BY_ZERO); } return result; } /** * @dev Variant of {tryModExp} that supports inputs of arbitrary length. */ function tryModExp( bytes memory b, bytes memory e, bytes memory m ) internal view returns (bool success, bytes memory result) { if (_zeroBytes(m)) return (false, new bytes(0)); uint256 mLen = m.length; // Encode call args in result and move the free memory pointer result = abi.encodePacked(b.length, e.length, mLen, b, e, m); assembly ("memory-safe") { let dataPtr := add(result, 0x20) // Write result on top of args to avoid allocating extra memory. success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen) // Overwrite the length. // result.length > returndatasize() is guaranteed because returndatasize() == m.length mstore(result, mLen) // Set the memory pointer after the returned data. mstore(0x40, add(dataPtr, mLen)) } } /** * @dev Returns whether the provided byte array is zero. */ function _zeroBytes(bytes memory byteArray) private pure returns (bool) { for (uint256 i = 0; i < byteArray.length; ++i) { if (byteArray[i] != 0) { return false; } } return true; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded * towards zero. * * This method is based on Newton's method for computing square roots; the algorithm is restricted to only * using integer operations. */ function sqrt(uint256 a) internal pure returns (uint256) { unchecked { // Take care of easy edge cases when a == 0 or a == 1 if (a <= 1) { return a; } // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between // the current value as `ε_n = | x_n - sqrt(a) |`. // // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is // bigger than any uint256. // // By noticing that // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)` // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar // to the msb function. uint256 aa = a; uint256 xn = 1; if (aa >= (1 << 128)) { aa >>= 128; xn <<= 64; } if (aa >= (1 << 64)) { aa >>= 64; xn <<= 32; } if (aa >= (1 << 32)) { aa >>= 32; xn <<= 16; } if (aa >= (1 << 16)) { aa >>= 16; xn <<= 8; } if (aa >= (1 << 8)) { aa >>= 8; xn <<= 4; } if (aa >= (1 << 4)) { aa >>= 4; xn <<= 2; } if (aa >= (1 << 2)) { xn <<= 1; } // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1). // // We can refine our estimation by noticing that the middle of that interval minimizes the error. // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2). // This is going to be our x_0 (and ε_0) xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2) // From here, Newton's method give us: // x_{n+1} = (x_n + a / x_n) / 2 // // One should note that: // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a // = ((x_n² + a) / (2 * x_n))² - a // = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a // = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²) // = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²) // = (x_n² - a)² / (2 * x_n)² // = ((x_n² - a) / (2 * x_n))² // ≥ 0 // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n // // This gives us the proof of quadratic convergence of the sequence: // ε_{n+1} = | x_{n+1} - sqrt(a) | // = | (x_n + a / x_n) / 2 - sqrt(a) | // = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) | // = | (x_n - sqrt(a))² / (2 * x_n) | // = | ε_n² / (2 * x_n) | // = ε_n² / | (2 * x_n) | // // For the first iteration, we have a special case where x_0 is known: // ε_1 = ε_0² / | (2 * x_0) | // ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2))) // ≤ 2**(2*e-4) / (3 * 2**(e-1)) // ≤ 2**(e-3) / 3 // ≤ 2**(e-3-log2(3)) // ≤ 2**(e-4.5) // // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n: // ε_{n+1} = ε_n² / | (2 * x_n) | // ≤ (2**(e-k))² / (2 * 2**(e-1)) // ≤ 2**(2*e-2*k) / 2**e // ≤ 2**(e-2*k) xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5 xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9 xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18 xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36 xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72 // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either // sqrt(a) or sqrt(a) + 1. return xn - SafeCast.toUint(xn > a / xn); } } /** * @dev Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a); } } /** * @dev Return the log in base 2 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; uint256 exp; unchecked { exp = 128 * SafeCast.toUint(value > (1 << 128) - 1); value >>= exp; result += exp; exp = 64 * SafeCast.toUint(value > (1 << 64) - 1); value >>= exp; result += exp; exp = 32 * SafeCast.toUint(value > (1 << 32) - 1); value >>= exp; result += exp; exp = 16 * SafeCast.toUint(value > (1 << 16) - 1); value >>= exp; result += exp; exp = 8 * SafeCast.toUint(value > (1 << 8) - 1); value >>= exp; result += exp; exp = 4 * SafeCast.toUint(value > (1 << 4) - 1); value >>= exp; result += exp; exp = 2 * SafeCast.toUint(value > (1 << 2) - 1); value >>= exp; result += exp; result += SafeCast.toUint(value > 1); } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value); } } /** * @dev Return the log in base 10 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value); } } /** * @dev Return the log in base 256 of a positive value rounded towards zero. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; uint256 isGt; unchecked { isGt = SafeCast.toUint(value > (1 << 128) - 1); value >>= isGt * 128; result += isGt * 16; isGt = SafeCast.toUint(value > (1 << 64) - 1); value >>= isGt * 64; result += isGt * 8; isGt = SafeCast.toUint(value > (1 << 32) - 1); value >>= isGt * 32; result += isGt * 4; isGt = SafeCast.toUint(value > (1 << 16) - 1); value >>= isGt * 16; result += isGt * 2; result += SafeCast.toUint(value > (1 << 8) - 1); } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value); } } /** * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers. */ function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) { return uint8(rounding) % 2 == 1; } }src/OrderRouter.sol
// SPDX-License-Identifier: LGPL-3.0 pragma solidity ^0.8.20; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {ERC1155HolderUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol"; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol"; import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol"; import {FixedProductMarketMaker} from "./FixedProductMarketMaker.sol"; import {IFixedProductMarketMaker} from "./interfaces/IFixedProductMarketMaker.sol"; import {ConditionalTokens} from "./ConditionalTokens.sol"; /// @title OrderRouter /// @notice Factory and routing hub for per-market FixedProductMarketMaker clones. /// Each market gets its own FPMM clone deployed at `createPool` time. /// All mutating calls (addFunding, buy, sell, etc.) are restricted to /// the designated `caller` (PredictionMarketCore). contract OrderRouter is ERC1155HolderUpgradeable, ReentrancyGuardUpgradeable, UUPSUpgradeable, Ownable2StepUpgradeable { using SafeERC20 for IERC20; error MaxAmountExceeded(); error NotCaller(); error PoolAlreadyExists(); error ZeroAddress(); error InvalidFee(); error InvalidTradingWindow(); /// @notice Parameters for deploying a new FPMM clone and its ConditionalTokens condition. struct CreatePoolParams { bytes32 conditionId; // CT condition; must already be prepared IERC20 collateralToken; // ERC-20 used as the market's collateral uint256 fee; // LP fee rate in WAD (1e18 = 100%); must be < 1e18 uint64 tradingStart; // unix timestamp trading opens (0 = immediate) uint64 tradingClose; // unix timestamp trading closes (0 = no close) address activator; // address allowed to open trading before tradingStart } /// @notice Address of the FPMM implementation contract cloned for each new market. address public fpmm_implementation; /// @notice The ConditionalTokens contract that issues outcome ERC-1155 positions. ConditionalTokens public conditionalTokens; /// @notice The single address authorised to call mutating functions (PredictionMarketCore proxy). address public caller; /// @notice Per-market FPMM clone, keyed by conditionId. mapping(bytes32 => IFixedProductMarketMaker) public marketMakers; event CallerSet(address indexed caller); modifier onlyCaller() { if (msg.sender != caller) revert NotCaller(); _; } /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } /// @notice Initialise the proxy. Called once by the deployment script immediately after the ERC1967Proxy is created. /// @param fpmmImpl_ FPMM implementation address to clone for each new market. /// @param ct_ ConditionalTokens contract that mints/burns outcome positions. /// @param owner_ Initial owner; receives `onlyOwner` privileges (upgrade, setCaller). function initialize(address fpmmImpl_, ConditionalTokens ct_, address owner_) external initializer { if (fpmmImpl_ == address(0)) revert ZeroAddress(); if (address(ct_) == address(0)) revert ZeroAddress(); if (owner_ == address(0)) revert ZeroAddress(); __ERC1155Holder_init(); __ReentrancyGuard_init(); __Ownable_init(owner_); __UUPSUpgradeable_init(); fpmm_implementation = fpmmImpl_; conditionalTokens = ct_; } function _authorizeUpgrade(address) internal override onlyOwner {} /// @notice Set the address authorised to call all `onlyCaller` functions. /// In production this is always the PredictionMarketCore proxy. /// @param caller_ New caller address; must be non-zero. function setCaller(address caller_) external onlyOwner { if (caller_ == address(0)) revert ZeroAddress(); caller = caller_; emit CallerSet(caller_); } uint256[46] private __gap; // ---- pool creation --------------------------------------------------- /// @notice Deploy a new FPMM clone for `p.conditionId` and grant it ERC-1155 approval /// so it can pull outcome tokens from this contract during sell operations. /// @param p Pool parameters; `conditionId` must not already have a pool. /// @return market Address of the freshly deployed FPMM clone. function createPool(CreatePoolParams calldata p) external onlyCaller returns (address market) { if (p.conditionId == bytes32(0)) revert ZeroAddress(); if (address(p.collateralToken) == address(0)) revert ZeroAddress(); if (p.fee >= 1e18) revert InvalidFee(); if (p.tradingClose != 0 && p.tradingStart != 0 && p.tradingClose <= p.tradingStart) revert InvalidTradingWindow(); if (address(marketMakers[p.conditionId]) != address(0)) revert PoolAlreadyExists(); market = Clones.clone(fpmm_implementation); FixedProductMarketMaker(market).initialize( conditionalTokens, p.conditionId, p.collateralToken, p.fee, p.tradingStart, p.tradingClose, p.activator, address(this) ); marketMakers[p.conditionId] = IFixedProductMarketMaker(market); // Allow the FPMM to pull outcome tokens from this contract on sell. conditionalTokens.setApprovalForAll(market, true); } /// @notice Update the trading-start time for a market that has not yet opened. /// Forwards to the FPMM, which enforces that only the activator may call this. /// @param conditionId Target market. /// @param newTradingStart New unix timestamp for when trading opens (0 = open immediately). /// @param activator_ Address asserting it is the activator; the FPMM validates this. function setTradingStart(bytes32 conditionId, uint64 newTradingStart, address activator_) external onlyCaller { marketMakers[conditionId].setTradingStart(newTradingStart, activator_); } // ---- liquidity ------------------------------------------------------- /// @notice Pull collateral from `msg.sender` (PMC), add it to the FPMM pool, and /// forward the minted LP shares and any return outcome tokens back to PMC. /// @param conditionId Target market. /// @param addedFunds Collateral amount to add; PMC must have approved this contract. /// @param context ABI-encoded `uint256[]` distribution hint for initial price skew. /// @return positionData ABI-encoded `uint256` LP shares minted. function addLiquidity(bytes32 conditionId, uint256 addedFunds, bytes calldata context) external onlyCaller nonReentrant returns (bytes memory positionData) { uint256[] memory distributionHint = abi.decode(context, (uint256[])); IFixedProductMarketMaker fpmm = marketMakers[conditionId]; IERC20 collateral = fpmm.collateralToken(); collateral.safeTransferFrom(msg.sender, address(this), addedFunds); collateral.forceApprove(address(fpmm), addedFunds); uint256 mintAmount = fpmm.addFunding(addedFunds, distributionHint); // Forward LP shares (ERC-20) to caller. IERC20(address(fpmm)).safeTransfer(msg.sender, mintAmount); _forwardOutcomeTokens(conditionId, msg.sender); positionData = abi.encode(mintAmount); } /// @notice Burn LP shares and return collateral + outcome tokens to PMC. /// PMC must transfer the LP shares to this contract before calling. /// @param conditionId Target market. /// @param positionData ABI-encoded `uint256` shares to burn (mirrors addLiquidity return). /// @param account Original LP; fees are settled to this address atomically inside the FPMM. function removeLiquidity(bytes32 conditionId, bytes calldata positionData, address account) external onlyCaller nonReentrant { uint256 sharesToBurn = abi.decode(positionData, (uint256)); // Caller (PMC) must have already transferred LP shares to this contract. IFixedProductMarketMaker fpmm = marketMakers[conditionId]; fpmm.removeFunding(sharesToBurn, account); _forwardOutcomeTokens(conditionId, msg.sender); } // ---- trading --------------------------------------------------------- /// @notice Pull collateral from PMC, execute a buy on the FPMM, and forward the /// purchased outcome tokens back to PMC. /// @param conditionId Target market. /// @param investmentAmount Collateral to invest (after venue/creator fee deduction by PMC). /// @param indexSet Bitmask of outcome slots to buy (e.g. 0b01 = outcome 0 only). /// @param minOutcomeTokensToBuy Slippage guard; reverts if fewer tokens would be received. /// @return outcomeTokensBought Number of outcome tokens received from the FPMM. function buy(bytes32 conditionId, uint256 investmentAmount, uint256 indexSet, uint256 minOutcomeTokensToBuy) external onlyCaller nonReentrant returns (uint256 outcomeTokensBought) { IFixedProductMarketMaker fpmm = marketMakers[conditionId]; IERC20 collateral = fpmm.collateralToken(); collateral.safeTransferFrom(msg.sender, address(this), investmentAmount); collateral.forceApprove(address(fpmm), investmentAmount); outcomeTokensBought = fpmm.buy(investmentAmount, indexSet, minOutcomeTokensToBuy); _forwardOutcomeTokens(conditionId, msg.sender); } /// @notice Transfer outcome tokens from PMC to this contract, execute a sell on the FPMM, /// and forward the returned collateral to PMC. /// @dev `exactOutcomeTokensSold` is pre-computed by PMC via `calcSellAmount` — passing it /// here avoids a duplicate on-chain calculation inside FPMM.sell. /// @param conditionId Target market. /// @param returnAmount Collateral the FPMM returns (before venue/creator fee deduction by PMC). /// @param outcomeIndex Zero-based index of the outcome slot being sold. /// @param exactOutcomeTokensSold Tokens to hand to the FPMM; must equal `calcSellAmount(returnAmount, outcomeIndex)`. /// @return outcomeTokensSold Equal to `exactOutcomeTokensSold`. function sell(bytes32 conditionId, uint256 returnAmount, uint256 outcomeIndex, uint256 exactOutcomeTokensSold) external onlyCaller nonReentrant returns (uint256 outcomeTokensSold) { IFixedProductMarketMaker fpmm = marketMakers[conditionId]; uint256[] memory ids = fpmm.positionIds(); IERC1155(address(conditionalTokens)).safeTransferFrom( msg.sender, address(this), ids[outcomeIndex], exactOutcomeTokensSold, "" ); fpmm.sell(returnAmount, outcomeIndex, exactOutcomeTokensSold, exactOutcomeTokensSold); outcomeTokensSold = exactOutcomeTokensSold; fpmm.collateralToken().safeTransfer(msg.sender, returnAmount); } // ---- fee withdrawal -------------------------------------------------- /// @notice Trigger LP fee withdrawal for `account` from the market's FPMM and /// forward the collateral to the caller (PredictionMarketCore), which /// pays the user. Keeps all collateral exits funnelled through a single /// static address. /// @param conditionId Target market. /// @param account Address whose accrued LP fees are settled. /// @return paid Collateral amount forwarded to the caller. function withdrawFees(bytes32 conditionId, address account) external onlyCaller returns (uint256 paid) { IFixedProductMarketMaker fpmm = marketMakers[conditionId]; paid = fpmm.withdrawFees(account); if (paid > 0) { fpmm.collateralToken().safeTransfer(msg.sender, paid); } } /// @notice Withdraw `account`'s accrued LP fees across many markets, aggregate /// them per collateral token, and forward each token's total to the /// caller (PredictionMarketCore). Keeping the per-market loop and the /// mechanism/collateral knowledge here lets the caller stay agnostic — /// a future CLOB mechanism can settle a batch from its vault without /// changing the caller. /// @param conditionIds Markets to claim from. /// @param account Address whose accrued LP fees are settled. /// @return tokens Collateral tokens touched; entries past the distinct count are zero. /// @return amounts Aggregate forwarded per matching `tokens` entry; zero entries are padding. function withdrawFeesMany(bytes32[] calldata conditionIds, address account) external onlyCaller returns (IERC20[] memory tokens, uint256[] memory amounts) { uint256 n = conditionIds.length; tokens = new IERC20[](n); amounts = new uint256[](n); uint256 uniq; for (uint256 i = 0; i < n; i++) { IFixedProductMarketMaker fpmm = marketMakers[conditionIds[i]]; uint256 paid = fpmm.withdrawFees(account); if (paid == 0) continue; IERC20 token = fpmm.collateralToken(); uint256 j; for (; j < uniq; j++) { if (tokens[j] == token) { amounts[j] += paid; break; } } if (j == uniq) { tokens[uniq] = token; amounts[uniq] = paid; uniq++; } } for (uint256 k = 0; k < uniq; k++) { tokens[k].safeTransfer(msg.sender, amounts[k]); } } // ---- view passthroughs ---------------------------------------------- /// @notice Quote how many outcome tokens `investmentAmount` collateral would buy. /// @param conditionId Target market. /// @param investmentAmount Collateral in (after fees); same units as the market collateral token. /// @param indexSet Outcome bitmask to price. /// @return Outcome tokens that would be received. function calcBuyAmount(bytes32 conditionId, uint256 investmentAmount, uint256 indexSet) external view returns (uint256) { return marketMakers[conditionId].calcBuyAmount(investmentAmount, indexSet); } /// @notice Quote how many outcome tokens must be sold to receive `returnAmount` collateral. /// @param conditionId Target market. /// @param returnAmount Desired collateral out; same units as the market collateral token. /// @param outcomeIndex Zero-based slot index being sold. /// @return Outcome tokens that must be provided to the FPMM. function calcSellAmount(bytes32 conditionId, uint256 returnAmount, uint256 outcomeIndex) external view returns (uint256) { return marketMakers[conditionId].calcSellAmount(returnAmount, outcomeIndex); } /// @notice Current AMM reserve for each outcome slot. /// @return One entry per outcome slot, in the same order as `positionIds`. function getPoolBalances(bytes32 conditionId) external view returns (uint256[] memory) { return marketMakers[conditionId].getPoolBalances(); } /// @notice ERC-1155 token IDs for each outcome position of the market. /// @return One position ID per outcome slot; index matches outcome index used in buy/sell. function positionIds(bytes32 conditionId) external view returns (uint256[] memory) { return marketMakers[conditionId].positionIds(); } /// @notice LP fees accrued and withdrawable by `account` from a market. /// @return Collateral amount available to withdraw, in market collateral token units. function feesWithdrawableBy(bytes32 conditionId, address account) external view returns (uint256) { return marketMakers[conditionId].feesWithdrawableBy(account); } /// @notice Address of the LP token (ERC-20) for a market — the FPMM clone itself. function lpToken(bytes32 conditionId) external view returns (address) { return address(marketMakers[conditionId]); } /// @notice Key pool parameters in a single call. /// @return collateralToken_ ERC-20 used as collateral. /// @return outcomeSlotCount_ Number of outcome slots. /// @return tradingStart_ Unix timestamp trading opens (0 = already open). /// @return tradingClose_ Unix timestamp trading closes (0 = no close). /// @return fee_ LP fee rate in WAD. /// @return feePoolWeight_ Accumulated fee pool weight used for LP fee accounting. function poolInfo(bytes32 conditionId) external view returns ( IERC20 collateralToken_, uint8 outcomeSlotCount_, uint64 tradingStart_, uint64 tradingClose_, uint256 fee_, uint256 feePoolWeight_ ) { return marketMakers[conditionId].poolInfo(); } // ---- internal -------------------------------------------------------- function _forwardOutcomeTokens(bytes32 conditionId, address to) internal { uint256[] memory ids = marketMakers[conditionId].positionIds(); uint256 n = ids.length; address[] memory addrs = new address[](n); for (uint256 i = 0; i < n; i++) addrs[i] = address(this); uint256[] memory bals = IERC1155(address(conditionalTokens)).balanceOfBatch(addrs, ids); bool any; for (uint256 i = 0; i < n; i++) if (bals[i] > 0) { any = true; break; } if (any) IERC1155(address(conditionalTokens)).safeBatchTransferFrom(address(this), to, ids, bals, ""); } }lib/openzeppelin-contracts-upgradeable/contracts/utils/cryptography/EIP712Upgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/EIP712.sol) pragma solidity ^0.8.20; import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol"; import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data. * * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the * separator from the immutable values, which is cheaper than accessing a cached version in cold storage. */ abstract contract EIP712Upgradeable is Initializable, IERC5267 { bytes32 private constant TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /// @custom:storage-location erc7201:openzeppelin.storage.EIP712 struct EIP712Storage { /// @custom:oz-renamed-from _HASHED_NAME bytes32 _hashedName; /// @custom:oz-renamed-from _HASHED_VERSION bytes32 _hashedVersion; string _name; string _version; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100; function _getEIP712Storage() private pure returns (EIP712Storage storage $) { assembly { $.slot := EIP712StorageLocation } } /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal onlyInitializing { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing { EIP712Storage storage $ = _getEIP712Storage(); $._name = name; $._version = version; // Reset prior values in storage if upgrading $._hashedName = 0; $._hashedVersion = 0; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(); } function _buildDomainSeparator() private view returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev See {IERC-5267}. */ function eip712Domain() public view virtual returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ) { EIP712Storage storage $ = _getEIP712Storage(); // If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized // and the EIP712 domain is not reliable, as it will be missing name and version. require($._hashedName == 0 && $._hashedVersion == 0, "EIP712: Uninitialized"); return ( hex"0f", // 01111 _EIP712Name(), _EIP712Version(), block.chainid, address(this), bytes32(0), new uint256[](0) ); } /** * @dev The name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712Name() internal view virtual returns (string memory) { EIP712Storage storage $ = _getEIP712Storage(); return $._name; } /** * @dev The version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712Version() internal view virtual returns (string memory) { EIP712Storage storage $ = _getEIP712Storage(); return $._version; } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead. */ function _EIP712NameHash() internal view returns (bytes32) { EIP712Storage storage $ = _getEIP712Storage(); string memory name = _EIP712Name(); if (bytes(name).length > 0) { return keccak256(bytes(name)); } else { // If the name is empty, the contract may have been upgraded without initializing the new storage. // We return the name hash in storage if non-zero, otherwise we assume the name is empty by design. bytes32 hashedName = $._hashedName; if (hashedName != 0) { return hashedName; } else { return keccak256(""); } } } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead. */ function _EIP712VersionHash() internal view returns (bytes32) { EIP712Storage storage $ = _getEIP712Storage(); string memory version = _EIP712Version(); if (bytes(version).length > 0) { return keccak256(bytes(version)); } else { // If the version is empty, the contract may have been upgraded without initializing the new storage. // We return the version hash in storage if non-zero, otherwise we assume the version is empty by design. bytes32 hashedVersion = $._hashedVersion; if (hashedVersion != 0) { return hashedVersion; } else { return keccak256(""); } } } }lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; import {IERC1363} from "../../../interfaces/IERC1363.sol"; import {Address} from "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC-20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { /** * @dev An operation with an ERC-20 token failed. */ error SafeERC20FailedOperation(address token); /** * @dev Indicates a failed `decreaseAllowance` request. */ error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease); /** * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value))); } /** * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. */ function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value))); } /** * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. * * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client" * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior. */ function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); forceApprove(token, spender, oldAllowance + value); } /** * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no * value, non-reverting calls are assumed to be successful. * * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client" * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal { unchecked { uint256 currentAllowance = token.allowance(address(this), spender); if (currentAllowance < requestedDecrease) { revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease); } forceApprove(token, spender, currentAllowance - requestedDecrease); } } /** * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval * to be set to zero before setting it to a non-zero value, such as USDT. * * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being * set here. */ function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value)); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0))); _callOptionalReturn(token, approvalCall); } } /** * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when * targeting contracts. * * Reverts if the returned value is other than `true`. */ function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal { if (to.code.length == 0) { safeTransfer(token, to, value); } else if (!token.transferAndCall(to, value, data)) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when * targeting contracts. * * Reverts if the returned value is other than `true`. */ function transferFromAndCallRelaxed( IERC1363 token, address from, address to, uint256 value, bytes memory data ) internal { if (to.code.length == 0) { safeTransferFrom(token, from, to, value); } else if (!token.transferFromAndCall(from, to, value, data)) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when * targeting contracts. * * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}. * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall} * once without retrying, and relies on the returned value to be true. * * Reverts if the returned value is other than `true`. */ function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal { if (to.code.length == 0) { forceApprove(token, to, value); } else if (!token.approveAndCall(to, value, data)) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements. */ function _callOptionalReturn(IERC20 token, bytes memory data) private { uint256 returnSize; uint256 returnValue; assembly ("memory-safe") { let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20) // bubble errors if iszero(success) { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize()) revert(ptr, returndatasize()) } returnSize := returndatasize() returnValue := mload(0) } if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { bool success; uint256 returnSize; uint256 returnValue; assembly ("memory-safe") { success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20) returnSize := returndatasize() returnValue := mload(0) } return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1); } }lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.20; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS } /** * @dev The signature derives the `address(0)`. */ error ECDSAInvalidSignature(); /** * @dev The signature has an invalid length. */ error ECDSAInvalidSignatureLength(uint256 length); /** * @dev The signature has an S value that is in the upper half order. */ error ECDSAInvalidSignatureS(bytes32 s); /** * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not * return address(0) without also returning an error description. Errors are documented using an enum (error type) * and a bytes32 providing additional information about the error. * * If no error is returned, then the address can be used for verification purposes. * * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function tryRecover( bytes32 hash, bytes memory signature ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly ("memory-safe") { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length)); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature); _throwError(error, errorArg); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures] */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) { unchecked { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); // We do not check for an overflow here since the shift operation results in 0 or 1. uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. */ function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs); _throwError(error, errorArg); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS, s); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature, bytes32(0)); } return (signer, RecoverError.NoError, bytes32(0)); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s); _throwError(error, errorArg); return recovered; } /** * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided. */ function _throwError(RecoverError error, bytes32 errorArg) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert ECDSAInvalidSignature(); } else if (error == RecoverError.InvalidSignatureLength) { revert ECDSAInvalidSignatureLength(uint256(errorArg)); } else if (error == RecoverError.InvalidSignatureS) { revert ECDSAInvalidSignatureS(errorArg); } } }lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol) pragma solidity ^0.8.20; /** * @dev Helper library for emitting standardized panic codes. * * ```solidity * contract Example { * using Panic for uint256; * * // Use any of the declared internal constants * function foo() { Panic.GENERIC.panic(); } * * // Alternatively * function foo() { Panic.panic(Panic.GENERIC); } * } * ``` * * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil]. * * _Available since v5.1._ */ // slither-disable-next-line unused-state library Panic { /// @dev generic / unspecified error uint256 internal constant GENERIC = 0x00; /// @dev used by the assert() builtin uint256 internal constant ASSERT = 0x01; /// @dev arithmetic underflow or overflow uint256 internal constant UNDER_OVERFLOW = 0x11; /// @dev division or modulo by zero uint256 internal constant DIVISION_BY_ZERO = 0x12; /// @dev enum conversion error uint256 internal constant ENUM_CONVERSION_ERROR = 0x21; /// @dev invalid encoding in storage uint256 internal constant STORAGE_ENCODING_ERROR = 0x22; /// @dev empty array pop uint256 internal constant EMPTY_ARRAY_POP = 0x31; /// @dev array out of bounds access uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32; /// @dev resource error (too large allocation or too large array) uint256 internal constant RESOURCE_ERROR = 0x41; /// @dev calling invalid internal function uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51; /// @dev Reverts with a panic code. Recommended to use with /// the internal constants with predefined codes. function panic(uint256 code) internal pure { assembly ("memory-safe") { mstore(0x00, 0x4e487b71) mstore(0x20, code) revert(0x1c, 0x24) } } }src/interfaces/ISignatureTransfer.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; /// @notice Minimal subset of Uniswap Permit2's ISignatureTransfer used by PredictionMarketCore. /// Full spec: https://github.com/Uniswap/permit2/blob/main/src/interfaces/ISignatureTransfer.sol interface ISignatureTransfer { struct TokenPermissions { address token; uint256 amount; } struct PermitTransferFrom { TokenPermissions permitted; uint256 nonce; uint256 deadline; } struct SignatureTransferDetails { address to; uint256 requestedAmount; } function permitTransferFrom( PermitTransferFrom memory permit, SignatureTransferDetails calldata transferDetails, address owner, bytes calldata signature ) external; }lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Utils.sol) pragma solidity ^0.8.21; import {IBeacon} from "../beacon/IBeacon.sol"; import {IERC1967} from "../../interfaces/IERC1967.sol"; import {Address} from "../../utils/Address.sol"; import {StorageSlot} from "../../utils/StorageSlot.sol"; /** * @dev This library provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots. */ library ERC1967Utils { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1. */ // solhint-disable-next-line private-vars-leading-underscore bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev The `implementation` of the proxy is invalid. */ error ERC1967InvalidImplementation(address implementation); /** * @dev The `admin` of the proxy is invalid. */ error ERC1967InvalidAdmin(address admin); /** * @dev The `beacon` of the proxy is invalid. */ error ERC1967InvalidBeacon(address beacon); /** * @dev An upgrade function sees `msg.value > 0` that may be lost. */ error ERC1967NonPayable(); /** * @dev Returns the current implementation address. */ function getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the ERC-1967 implementation slot. */ function _setImplementation(address newImplementation) private { if (newImplementation.code.length == 0) { revert ERC1967InvalidImplementation(newImplementation); } StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Performs implementation upgrade with additional setup call if data is nonempty. * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected * to avoid stuck value in the contract. * * Emits an {IERC1967-Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) internal { _setImplementation(newImplementation); emit IERC1967.Upgraded(newImplementation); if (data.length > 0) { Address.functionDelegateCall(newImplementation, data); } else { _checkNonPayable(); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ // solhint-disable-next-line private-vars-leading-underscore bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Returns the current admin. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(ADMIN_SLOT).value; } /** * @dev Stores a new address in the ERC-1967 admin slot. */ function _setAdmin(address newAdmin) private { if (newAdmin == address(0)) { revert ERC1967InvalidAdmin(address(0)); } StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {IERC1967-AdminChanged} event. */ function changeAdmin(address newAdmin) internal { emit IERC1967.AdminChanged(getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1. */ // solhint-disable-next-line private-vars-leading-underscore bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Returns the current beacon. */ function getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(BEACON_SLOT).value; } /** * @dev Stores a new beacon in the ERC-1967 beacon slot. */ function _setBeacon(address newBeacon) private { if (newBeacon.code.length == 0) { revert ERC1967InvalidBeacon(newBeacon); } StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon; address beaconImplementation = IBeacon(newBeacon).implementation(); if (beaconImplementation.code.length == 0) { revert ERC1967InvalidImplementation(beaconImplementation); } } /** * @dev Change the beacon and trigger a setup call if data is nonempty. * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected * to avoid stuck value in the contract. * * Emits an {IERC1967-BeaconUpgraded} event. * * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for * efficiency. */ function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal { _setBeacon(newBeacon); emit IERC1967.BeaconUpgraded(newBeacon); if (data.length > 0) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } else { _checkNonPayable(); } } /** * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract * if an upgrade doesn't perform an initialization call. */ function _checkNonPayable() private { if (msg.value > 0) { revert ERC1967NonPayable(); } } }lib/openzeppelin-contracts-upgradeable/contracts/utils/MulticallUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.1) (utils/Multicall.sol) pragma solidity ^0.8.20; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {ContextUpgradeable} from "./ContextUpgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Provides a function to batch together multiple calls in a single external call. * * Consider any assumption about calldata validation performed by the sender may be violated if it's not especially * careful about sending transactions invoking {multicall}. For example, a relay address that filters function * selectors won't filter calls nested within a {multicall} operation. * * NOTE: Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. `msg.sender` is not {_msgSender}). * If a non-canonical context is identified, the following self `delegatecall` appends the last bytes of `msg.data` * to the subcall. This makes it safe to use with {ERC2771Context}. Contexts that don't affect the resolution of * {_msgSender} are not propagated to subcalls. */ abstract contract MulticallUpgradeable is Initializable, ContextUpgradeable { function __Multicall_init() internal onlyInitializing { } function __Multicall_init_unchained() internal onlyInitializing { } /** * @dev Receives and executes a batch of function calls on this contract. * @custom:oz-upgrades-unsafe-allow-reachable delegatecall */ function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) { bytes memory context = msg.sender == _msgSender() ? new bytes(0) : msg.data[msg.data.length - _contextSuffixLength():]; results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context)); } return results; } }lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.20; import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol"; import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol"; import {Initializable} from "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. */ abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable { /// @custom:oz-upgrades-unsafe-allow state-variable-immutable address private immutable __self = address(this); /** * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)` * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called, * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string. * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function * during an upgrade. */ string public constant UPGRADE_INTERFACE_VERSION = "5.0.0"; /** * @dev The call is from an unauthorized context. */ error UUPSUnauthorizedCallContext(); /** * @dev The storage `slot` is unsupported as a UUID. */ error UUPSUnsupportedProxiableUUID(bytes32 slot); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { _checkProxy(); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { _checkNotDelegated(); _; } function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /** * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate the implementation's compatibility when performing an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual notDelegated returns (bytes32) { return ERC1967Utils.IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. * * @custom:oz-upgrades-unsafe-allow-reachable delegatecall */ function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data); } /** * @dev Reverts if the execution is not performed via delegatecall or the execution * context is not of a proxy with an ERC-1967 compliant implementation pointing to self. * See {_onlyProxy}. */ function _checkProxy() internal view virtual { if ( address(this) == __self || // Must be called through delegatecall ERC1967Utils.getImplementation() != __self // Must be called through an active proxy ) { revert UUPSUnauthorizedCallContext(); } } /** * @dev Reverts if the execution is performed via delegatecall. * See {notDelegated}. */ function _checkNotDelegated() internal view virtual { if (address(this) != __self) { // Must not be called through delegatecall revert UUPSUnauthorizedCallContext(); } } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; /** * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call. * * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value * is expected to be the implementation slot in ERC-1967. * * Emits an {IERC1967-Upgraded} event. */ function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private { try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) { if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) { revert UUPSUnsupportedProxiableUUID(slot); } ERC1967Utils.upgradeToAndCall(newImplementation, data); } catch { // The implementation is not UUPS revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation); } } }lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol"; import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC-20 * applications. */ abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors { /// @custom:storage-location erc7201:openzeppelin.storage.ERC20 struct ERC20Storage { mapping(address account => uint256) _balances; mapping(address account => mapping(address spender => uint256)) _allowances; uint256 _totalSupply; string _name; string _symbol; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00; function _getERC20Storage() private pure returns (ERC20Storage storage $) { assembly { $.slot := ERC20StorageLocation } } /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { ERC20Storage storage $ = _getERC20Storage(); $._name = name_; $._symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { ERC20Storage storage $ = _getERC20Storage(); return $._name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { ERC20Storage storage $ = _getERC20Storage(); return $._symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `value`. */ function transfer(address to, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _transfer(owner, to, value); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Skips emitting an {Approval} event indicating an allowance update. This is not * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve]. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `value`. * - the caller must have allowance for ``from``'s tokens of at least * `value`. */ function transferFrom(address from, address to, uint256 value) public virtual returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, value); _transfer(from, to, value); return true; } /** * @dev Moves a `value` amount of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _transfer(address from, address to, uint256 value) internal { if (from == address(0)) { revert ERC20InvalidSender(address(0)); } if (to == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(from, to, value); } /** * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from` * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding * this function. * * Emits a {Transfer} event. */ function _update(address from, address to, uint256 value) internal virtual { ERC20Storage storage $ = _getERC20Storage(); if (from == address(0)) { // Overflow check required: The rest of the code assumes that totalSupply never overflows $._totalSupply += value; } else { uint256 fromBalance = $._balances[from]; if (fromBalance < value) { revert ERC20InsufficientBalance(from, fromBalance, value); } unchecked { // Overflow not possible: value <= fromBalance <= totalSupply. $._balances[from] = fromBalance - value; } } if (to == address(0)) { unchecked { // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply. $._totalSupply -= value; } } else { unchecked { // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256. $._balances[to] += value; } } emit Transfer(from, to, value); } /** * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). * Relies on the `_update` mechanism * * Emits a {Transfer} event with `from` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _mint(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(address(0), account, value); } /** * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply. * Relies on the `_update` mechanism. * * Emits a {Transfer} event with `to` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead */ function _burn(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidSender(address(0)); } _update(account, address(0), value); } /** * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument. */ function _approve(address owner, address spender, uint256 value) internal { _approve(owner, spender, value, true); } /** * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event. * * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any * `Approval` event during `transferFrom` operations. * * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to * true using the following override: * * ```solidity * function _approve(address owner, address spender, uint256 value, bool) internal virtual override { * super._approve(owner, spender, value, true); * } * ``` * * Requirements are the same as {_approve}. */ function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { ERC20Storage storage $ = _getERC20Storage(); if (owner == address(0)) { revert ERC20InvalidApprover(address(0)); } if (spender == address(0)) { revert ERC20InvalidSpender(address(0)); } $._allowances[owner][spender] = value; if (emitEvent) { emit Approval(owner, spender, value); } } /** * @dev Updates `owner` s allowance for `spender` based on spent `value`. * * Does not update the allowance value in case of infinite allowance. * Revert if not enough allowance is available. * * Does not emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 value) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { if (currentAllowance < value) { revert ERC20InsufficientAllowance(spender, currentAllowance, value); } unchecked { _approve(owner, spender, currentAllowance - value, false); } } } }lib/openzeppelin-contracts/contracts/token/ERC1155/ERC1155.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.20; import {IERC1155} from "./IERC1155.sol"; import {IERC1155MetadataURI} from "./extensions/IERC1155MetadataURI.sol"; import {ERC1155Utils} from "./utils/ERC1155Utils.sol"; import {Context} from "../../utils/Context.sol"; import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol"; import {Arrays} from "../../utils/Arrays.sol"; import {IERC1155Errors} from "../../interfaces/draft-IERC6093.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 */ abstract contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI, IERC1155Errors { using Arrays for uint256[]; using Arrays for address[]; mapping(uint256 id => mapping(address account => uint256)) private _balances; mapping(address account => mapping(address operator => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the ERC]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256 /* id */) public view virtual returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. */ function balanceOf(address account, uint256 id) public view virtual returns (uint256) { return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual returns (uint256[] memory) { if (accounts.length != ids.length) { revert ERC1155InvalidArrayLength(ids.length, accounts.length); } uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts.unsafeMemoryAccess(i), ids.unsafeMemoryAccess(i)); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) public virtual { address sender = _msgSender(); if (from != sender && !isApprovedForAll(from, sender)) { revert ERC1155MissingApprovalForAll(sender, from); } _safeTransferFrom(from, to, id, value, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) public virtual { address sender = _msgSender(); if (from != sender && !isApprovedForAll(from, sender)) { revert ERC1155MissingApprovalForAll(sender, from); } _safeBatchTransferFrom(from, to, ids, values, data); } /** * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`. Will mint (or burn) if `from` * (or `to`) is the zero address. * * Emits a {TransferSingle} event if the arrays contain one element, and {TransferBatch} otherwise. * * Requirements: * * - If `to` refers to a smart contract, it must implement either {IERC1155Receiver-onERC1155Received} * or {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value. * - `ids` and `values` must have the same length. * * NOTE: The ERC-1155 acceptance check is not performed in this function. See {_updateWithAcceptanceCheck} instead. */ function _update(address from, address to, uint256[] memory ids, uint256[] memory values) internal virtual { if (ids.length != values.length) { revert ERC1155InvalidArrayLength(ids.length, values.length); } address operator = _msgSender(); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids.unsafeMemoryAccess(i); uint256 value = values.unsafeMemoryAccess(i); if (from != address(0)) { uint256 fromBalance = _balances[id][from]; if (fromBalance < value) { revert ERC1155InsufficientBalance(from, fromBalance, value, id); } unchecked { // Overflow not possible: value <= fromBalance _balances[id][from] = fromBalance - value; } } if (to != address(0)) { _balances[id][to] += value; } } if (ids.length == 1) { uint256 id = ids.unsafeMemoryAccess(0); uint256 value = values.unsafeMemoryAccess(0); emit TransferSingle(operator, from, to, id, value); } else { emit TransferBatch(operator, from, to, ids, values); } } /** * @dev Version of {_update} that performs the token acceptance check by calling * {IERC1155Receiver-onERC1155Received} or {IERC1155Receiver-onERC1155BatchReceived} on the receiver address if it * contains code (eg. is a smart contract at the moment of execution). * * IMPORTANT: Overriding this function is discouraged because it poses a reentrancy risk from the receiver. So any * update to the contract state after this function would break the check-effect-interaction pattern. Consider * overriding {_update} instead. */ function _updateWithAcceptanceCheck( address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal virtual { _update(from, to, ids, values); if (to != address(0)) { address operator = _msgSender(); if (ids.length == 1) { uint256 id = ids.unsafeMemoryAccess(0); uint256 value = values.unsafeMemoryAccess(0); ERC1155Utils.checkOnERC1155Received(operator, from, to, id, value, data); } else { ERC1155Utils.checkOnERC1155BatchReceived(operator, from, to, ids, values, data); } } } /** * @dev Transfers a `value` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `value` amount. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) internal { if (to == address(0)) { revert ERC1155InvalidReceiver(address(0)); } if (from == address(0)) { revert ERC1155InvalidSender(address(0)); } (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value); _updateWithAcceptanceCheck(from, to, ids, values, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. * - `ids` and `values` must have the same length. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal { if (to == address(0)) { revert ERC1155InvalidReceiver(address(0)); } if (from == address(0)) { revert ERC1155InvalidSender(address(0)); } _updateWithAcceptanceCheck(from, to, ids, values, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the ERC]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the values in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates a `value` amount of tokens of type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address to, uint256 id, uint256 value, bytes memory data) internal { if (to == address(0)) { revert ERC1155InvalidReceiver(address(0)); } (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value); _updateWithAcceptanceCheck(address(0), to, ids, values, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `values` must have the same length. * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory values, bytes memory data) internal { if (to == address(0)) { revert ERC1155InvalidReceiver(address(0)); } _updateWithAcceptanceCheck(address(0), to, ids, values, data); } /** * @dev Destroys a `value` amount of tokens of type `id` from `from` * * Emits a {TransferSingle} event. * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `value` amount of tokens of type `id`. */ function _burn(address from, uint256 id, uint256 value) internal { if (from == address(0)) { revert ERC1155InvalidSender(address(0)); } (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value); _updateWithAcceptanceCheck(from, address(0), ids, values, ""); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Emits a {TransferBatch} event. * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `value` amount of tokens of type `id`. * - `ids` and `values` must have the same length. */ function _burnBatch(address from, uint256[] memory ids, uint256[] memory values) internal { if (from == address(0)) { revert ERC1155InvalidSender(address(0)); } _updateWithAcceptanceCheck(from, address(0), ids, values, ""); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the zero address. */ function _setApprovalForAll(address owner, address operator, bool approved) internal virtual { if (operator == address(0)) { revert ERC1155InvalidOperator(address(0)); } _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Creates an array in memory with only one value for each of the elements provided. */ function _asSingletonArrays( uint256 element1, uint256 element2 ) private pure returns (uint256[] memory array1, uint256[] memory array2) { assembly ("memory-safe") { // Load the free memory pointer array1 := mload(0x40) // Set array length to 1 mstore(array1, 1) // Store the single element at the next word after the length (where content starts) mstore(add(array1, 0x20), element1) // Repeat for next array locating it right after the first array array2 := add(array1, 0x40) mstore(array2, 1) mstore(add(array2, 0x20), element2) // Update the free memory pointer by pointing after the second array mstore(0x40, add(array2, 0x40)) } } }lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "../token/ERC20/IERC20.sol";lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol) pragma solidity ^0.8.20; import {IERC165} from "../utils/introspection/IERC165.sol";lib/openzeppelin-contracts/contracts/utils/Arrays.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/Arrays.sol) // This file was procedurally generated from scripts/generate/templates/Arrays.js. pragma solidity ^0.8.20; import {Comparators} from "./Comparators.sol"; import {SlotDerivation} from "./SlotDerivation.sol"; import {StorageSlot} from "./StorageSlot.sol"; import {Math} from "./math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { using SlotDerivation for bytes32; using StorageSlot for bytes32; /** * @dev Sort an array of uint256 (in memory) following the provided comparator function. * * This function does the sorting "in place", meaning that it overrides the input. The object is returned for * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array. * * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may * consume more gas than is available in a block, leading to potential DoS. * * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way. */ function sort( uint256[] memory array, function(uint256, uint256) pure returns (bool) comp ) internal pure returns (uint256[] memory) { _quickSort(_begin(array), _end(array), comp); return array; } /** * @dev Variant of {sort} that sorts an array of uint256 in increasing order. */ function sort(uint256[] memory array) internal pure returns (uint256[] memory) { sort(array, Comparators.lt); return array; } /** * @dev Sort an array of address (in memory) following the provided comparator function. * * This function does the sorting "in place", meaning that it overrides the input. The object is returned for * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array. * * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may * consume more gas than is available in a block, leading to potential DoS. * * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way. */ function sort( address[] memory array, function(address, address) pure returns (bool) comp ) internal pure returns (address[] memory) { sort(_castToUint256Array(array), _castToUint256Comp(comp)); return array; } /** * @dev Variant of {sort} that sorts an array of address in increasing order. */ function sort(address[] memory array) internal pure returns (address[] memory) { sort(_castToUint256Array(array), Comparators.lt); return array; } /** * @dev Sort an array of bytes32 (in memory) following the provided comparator function. * * This function does the sorting "in place", meaning that it overrides the input. The object is returned for * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array. * * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may * consume more gas than is available in a block, leading to potential DoS. * * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way. */ function sort( bytes32[] memory array, function(bytes32, bytes32) pure returns (bool) comp ) internal pure returns (bytes32[] memory) { sort(_castToUint256Array(array), _castToUint256Comp(comp)); return array; } /** * @dev Variant of {sort} that sorts an array of bytes32 in increasing order. */ function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) { sort(_castToUint256Array(array), Comparators.lt); return array; } /** * @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops * at end (exclusive). Sorting follows the `comp` comparator. * * Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls. * * IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should * be used only if the limits are within a memory array. */ function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure { unchecked { if (end - begin < 0x40) return; // Use first element as pivot uint256 pivot = _mload(begin); // Position where the pivot should be at the end of the loop uint256 pos = begin; for (uint256 it = begin + 0x20; it < end; it += 0x20) { if (comp(_mload(it), pivot)) { // If the value stored at the iterator's position comes before the pivot, we increment the // position of the pivot and move the value there. pos += 0x20; _swap(pos, it); } } _swap(begin, pos); // Swap pivot into place _quickSort(begin, pos, comp); // Sort the left side of the pivot _quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot } } /** * @dev Pointer to the memory location of the first element of `array`. */ function _begin(uint256[] memory array) private pure returns (uint256 ptr) { assembly ("memory-safe") { ptr := add(array, 0x20) } } /** * @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word * that comes just after the last element of the array. */ function _end(uint256[] memory array) private pure returns (uint256 ptr) { unchecked { return _begin(array) + array.length * 0x20; } } /** * @dev Load memory word (as a uint256) at location `ptr`. */ function _mload(uint256 ptr) private pure returns (uint256 value) { assembly { value := mload(ptr) } } /** * @dev Swaps the elements memory location `ptr1` and `ptr2`. */ function _swap(uint256 ptr1, uint256 ptr2) private pure { assembly { let value1 := mload(ptr1) let value2 := mload(ptr2) mstore(ptr1, value2) mstore(ptr2, value1) } } /// @dev Helper: low level cast address memory array to uint256 memory array function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) { assembly { output := input } } /// @dev Helper: low level cast bytes32 memory array to uint256 memory array function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) { assembly { output := input } } /// @dev Helper: low level cast address comp function to uint256 comp function function _castToUint256Comp( function(address, address) pure returns (bool) input ) private pure returns (function(uint256, uint256) pure returns (bool) output) { assembly { output := input } } /// @dev Helper: low level cast bytes32 comp function to uint256 comp function function _castToUint256Comp( function(bytes32, bytes32) pure returns (bool) input ) private pure returns (function(uint256, uint256) pure returns (bool) output) { assembly { output := input } } /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * NOTE: The `array` is expected to be sorted in ascending order, and to * contain no repeated elements. * * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks * support for repeated elements in the array. The {lowerBound} function should * be used instead. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { uint256 low = 0; uint256 high = array.length; if (high == 0) { return 0; } while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds towards zero (it does integer division with truncation). if (unsafeAccess(array, mid).value > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && unsafeAccess(array, low - 1).value == element) { return low - 1; } else { return low; } } /** * @dev Searches an `array` sorted in ascending order and returns the first * index that contains a value greater or equal than `element`. If no such index * exists (i.e. all values in the array are strictly less than `element`), the array * length is returned. Time complexity O(log n). * * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound]. */ function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) { uint256 low = 0; uint256 high = array.length; if (high == 0) { return 0; } while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds towards zero (it does integer division with truncation). if (unsafeAccess(array, mid).value < element) { // this cannot overflow because mid < high unchecked { low = mid + 1; } } else { high = mid; } } return low; } /** * @dev Searches an `array` sorted in ascending order and returns the first * index that contains a value strictly greater than `element`. If no such index * exists (i.e. all values in the array are strictly less than `element`), the array * length is returned. Time complexity O(log n). * * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound]. */ function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { uint256 low = 0; uint256 high = array.length; if (high == 0) { return 0; } while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds towards zero (it does integer division with truncation). if (unsafeAccess(array, mid).value > element) { high = mid; } else { // this cannot overflow because mid < high unchecked { low = mid + 1; } } } return low; } /** * @dev Same as {lowerBound}, but with an array in memory. */ function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) { uint256 low = 0; uint256 high = array.length; if (high == 0) { return 0; } while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds towards zero (it does integer division with truncation). if (unsafeMemoryAccess(array, mid) < element) { // this cannot overflow because mid < high unchecked { low = mid + 1; } } else { high = mid; } } return low; } /** * @dev Same as {upperBound}, but with an array in memory. */ function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) { uint256 low = 0; uint256 high = array.length; if (high == 0) { return 0; } while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds towards zero (it does integer division with truncation). if (unsafeMemoryAccess(array, mid) > element) { high = mid; } else { // this cannot overflow because mid < high unchecked { low = mid + 1; } } } return low; } /** * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. * * WARNING: Only use if you are certain `pos` is lower than the array length. */ function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) { bytes32 slot; assembly ("memory-safe") { slot := arr.slot } return slot.deriveArray().offset(pos).getAddressSlot(); } /** * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. * * WARNING: Only use if you are certain `pos` is lower than the array length. */ function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) { bytes32 slot; assembly ("memory-safe") { slot := arr.slot } return slot.deriveArray().offset(pos).getBytes32Slot(); } /** * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. * * WARNING: Only use if you are certain `pos` is lower than the array length. */ function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) { bytes32 slot; assembly ("memory-safe") { slot := arr.slot } return slot.deriveArray().offset(pos).getUint256Slot(); } /** * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. * * WARNING: Only use if you are certain `pos` is lower than the array length. */ function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) { assembly { res := mload(add(add(arr, 0x20), mul(pos, 0x20))) } } /** * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. * * WARNING: Only use if you are certain `pos` is lower than the array length. */ function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) { assembly { res := mload(add(add(arr, 0x20), mul(pos, 0x20))) } } /** * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. * * WARNING: Only use if you are certain `pos` is lower than the array length. */ function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) { assembly { res := mload(add(add(arr, 0x20), mul(pos, 0x20))) } } /** * @dev Helper to set the length of an dynamic array. Directly writing to `.length` is forbidden. * * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased. */ function unsafeSetLength(address[] storage array, uint256 len) internal { assembly ("memory-safe") { sstore(array.slot, len) } } /** * @dev Helper to set the length of an dynamic array. Directly writing to `.length` is forbidden. * * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased. */ function unsafeSetLength(bytes32[] storage array, uint256 len) internal { assembly ("memory-safe") { sstore(array.slot, len) } } /** * @dev Helper to set the length of an dynamic array. Directly writing to `.length` is forbidden. * * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased. */ function unsafeSetLength(uint256[] storage array, uint256 len) internal { assembly ("memory-safe") { sstore(array.slot, len) } } }lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC-165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[ERC]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC-20 standard as defined in the ERC. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the value of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the value of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves a `value` amount of tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 value) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the * allowance mechanism. `value` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 value) external returns (bool); }src/interfaces/IFixedProductMarketMaker.sol
// SPDX-License-Identifier: LGPL-3.0 pragma solidity ^0.8.20; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {ConditionalTokens} from "../ConditionalTokens.sol"; interface IFixedProductMarketMaker is IERC20 { function conditionalTokens() external view returns (ConditionalTokens); function collateralToken() external view returns (IERC20); function conditionId() external view returns (bytes32); function outcomeSlotCount() external view returns (uint8); function tradingStart() external view returns (uint64); function tradingClose() external view returns (uint64); function fee() external view returns (uint256); function feePoolWeight() external view returns (uint256); function router() external view returns (address); function poolInfo() external view returns ( IERC20 collateralToken_, uint8 outcomeSlotCount_, uint64 tradingStart_, uint64 tradingClose_, uint256 fee_, uint256 feePoolWeight_ ); function positionIds() external view returns (uint256[] memory); function getPoolBalances() external view returns (uint256[] memory); function feesWithdrawableBy(address account) external view returns (uint256); function calcBuyAmount(uint256 investmentAmount, uint256 indexSet) external view returns (uint256); function calcSellAmount(uint256 returnAmount, uint256 outcomeIndex) external view returns (uint256); function addFunding(uint256 addedFunds, uint256[] calldata distributionHint) external returns (uint256 mintAmount); function removeFunding(uint256 sharesToBurn, address account) external; function buy(uint256 investmentAmount, uint256 indexSet, uint256 minOutcomeTokensToBuy) external returns (uint256 outcomeTokensBought); function sell(uint256 returnAmount, uint256 outcomeIndex, uint256 maxOutcomeTokensToSell, uint256 exactOutcomeTokensSold) external returns (uint256 outcomeTokensSold); function withdrawFees(address account) external returns (uint256); function setTradingStart(uint64 newTradingStart, address claimedActivator) external; }lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Utils.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/utils/ERC1155Utils.sol) pragma solidity ^0.8.20; import {IERC1155Receiver} from "../IERC1155Receiver.sol"; import {IERC1155Errors} from "../../../interfaces/draft-IERC6093.sol"; /** * @dev Library that provide common ERC-1155 utility functions. * * See https://eips.ethereum.org/EIPS/eip-1155[ERC-1155]. * * _Available since v5.1._ */ library ERC1155Utils { /** * @dev Performs an acceptance check for the provided `operator` by calling {IERC1155-onERC1155Received} * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`). * * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA). * Otherwise, the recipient must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value to accept * the transfer. */ function checkOnERC1155Received( address operator, address from, address to, uint256 id, uint256 value, bytes memory data ) internal { if (to.code.length > 0) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { // Tokens rejected revert IERC1155Errors.ERC1155InvalidReceiver(to); } } catch (bytes memory reason) { if (reason.length == 0) { // non-IERC1155Receiver implementer revert IERC1155Errors.ERC1155InvalidReceiver(to); } else { assembly ("memory-safe") { revert(add(32, reason), mload(reason)) } } } } } /** * @dev Performs a batch acceptance check for the provided `operator` by calling {IERC1155-onERC1155BatchReceived} * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`). * * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA). * Otherwise, the recipient must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value to accept * the transfer. */ function checkOnERC1155BatchReceived( address operator, address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal { if (to.code.length > 0) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { // Tokens rejected revert IERC1155Errors.ERC1155InvalidReceiver(to); } } catch (bytes memory reason) { if (reason.length == 0) { // non-IERC1155Receiver implementer revert IERC1155Errors.ERC1155InvalidReceiver(to); } else { assembly ("memory-safe") { revert(add(32, reason), mload(reason)) } } } } } }lib/openzeppelin-contracts/contracts/proxy/Clones.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (proxy/Clones.sol) pragma solidity ^0.8.20; import {Errors} from "../utils/Errors.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[ERC-1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { return clone(implementation, 0); } /** * @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency * to the new contract. * * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory) * to always have enough balance for new deployments. Consider exposing this function under a payable method. */ function clone(address implementation, uint256 value) internal returns (address instance) { if (address(this).balance < value) { revert Errors.InsufficientBalance(address(this).balance, value); } assembly ("memory-safe") { // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes // of the `implementation` address with the bytecode before the address. mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000)) // Packs the remaining 17 bytes of `implementation` with the bytecode after the address. mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3)) instance := create(value, 0x09, 0x37) } if (instance == address(0)) { revert Errors.FailedDeployment(); } } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { return cloneDeterministic(implementation, salt, 0); } /** * @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with * a `value` parameter to send native currency to the new contract. * * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory) * to always have enough balance for new deployments. Consider exposing this function under a payable method. */ function cloneDeterministic( address implementation, bytes32 salt, uint256 value ) internal returns (address instance) { if (address(this).balance < value) { revert Errors.InsufficientBalance(address(this).balance, value); } assembly ("memory-safe") { // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes // of the `implementation` address with the bytecode before the address. mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000)) // Packs the remaining 17 bytes of `implementation` with the bytecode after the address. mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3)) instance := create2(value, 0x09, 0x37, salt) } if (instance == address(0)) { revert Errors.FailedDeployment(); } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly ("memory-safe") { let ptr := mload(0x40) mstore(add(ptr, 0x38), deployer) mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff) mstore(add(ptr, 0x14), implementation) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73) mstore(add(ptr, 0x58), salt) mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37)) predicted := and(keccak256(add(ptr, 0x43), 0x55), 0xffffffffffffffffffffffffffffffffffffffff) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt ) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } }lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC-20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol) pragma solidity ^0.8.20; import {IERC20} from "./IERC20.sol"; import {IERC165} from "./IERC165.sol"; /** * @title IERC1363 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363]. * * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction. */ interface IERC1363 is IERC20, IERC165 { /* * Note: the ERC-165 identifier for this interface is 0xb0202a11. * 0xb0202a11 === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^ * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ /** * @dev Moves a `value` amount of tokens from the caller's account to `to` * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferAndCall(address to, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from the caller's account to `to` * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @param data Additional data with no specified format, sent in call to `to`. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param from The address which you want to send tokens from. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferFromAndCall(address from, address to, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param from The address which you want to send tokens from. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @param data Additional data with no specified format, sent in call to `to`. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function approveAndCall(address spender, uint256 value) external returns (bool); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @param data Additional data with no specified format, sent in call to `spender`. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool); }src/VenueRegistry.sol
// SPDX-License-Identifier: LGPL-3.0 pragma solidity ^0.8.20; import {IVenuePolicy} from "./interfaces/IVenuePolicy.sol"; import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol"; /// @title VenueRegistry /// @notice Permissionless registry of routing venues — frontends, aggregators, /// or any counterparty surfacing the headless protocol. Anyone can /// register; each venue self-manages its fee, recipient, signer, and /// enabled state. venueId 0 is reserved and never stored; the router /// treats it as "no venue, no fee, no signature". contract VenueRegistry is UUPSUpgradeable, Ownable2StepUpgradeable { error VenueFeeTooHigh(); error FeeRecipientRequired(); error SignerRequired(); error NotOwner(); error PendingOwnerOnly(); error UnknownVenue(); error VenueDisabled(); error ZeroOwner(); error VenueIdReserved(); error InvalidPolicy(); /// @notice Hard cap on venue fee. Matches the docs (10% / 1000 bps). uint16 public constant MAX_VENUE_FEE_BPS = 1000; struct Venue { address owner; // can update fields below address feeRecipient; // receives the trade-time venue fee address signer; // EIP-712 signer (zero ⇒ no sig path even if either requires* flag is set) uint16 venueFeeBps; // trade-time fee, ≤ MAX_VENUE_FEE_BPS bool requiresCreateSig; // if true, router enforces a venue-signed authorization on market-creation calls bool requiresTradeSig; // if true, router enforces a venue-signed authorization on buy/sell calls bool enabled; // venue can flip off to drain users (router rejects disabled venues) IVenuePolicy policy; // optional; address(0) = no policy uint16 marketFeeBps; // fee earned on trades in markets this venue created } event VenueRegistered( uint32 indexed venueId, address indexed owner, address feeRecipient, address signer, uint16 venueFeeBps, uint16 marketFeeBps, bool requiresCreateSig, bool requiresTradeSig, bool enabled, address policy ); event VenueUpdated( uint32 indexed venueId, address feeRecipient, address signer, uint16 venueFeeBps, uint16 marketFeeBps, bool requiresCreateSig, bool requiresTradeSig, bool enabled, address policy ); event VenueEnabledChanged(uint32 indexed venueId, bool enabled); event VenueOwnershipTransferStarted( uint32 indexed venueId, address indexed currentOwner, address indexed pendingOwner ); event VenueOwnershipTransferred(uint32 indexed venueId, address indexed oldOwner, address indexed newOwner); event VenuePolicySet(uint32 indexed venueId, address policy); /// @dev Auto-incrementing. `nextVenueId` is the id that will be assigned /// on the next `register` call. Starts at 1 so 0 stays reserved. uint32 public nextVenueId; mapping(uint32 => Venue) internal _venues; /// @notice Staged new owner for a pending two-step transfer. Zero means no /// transfer is in progress for that venueId. mapping(uint32 => address) public pendingOwner; /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } /// @notice Initialise the proxy. Called once immediately after the ERC1967Proxy is created. /// @param owner_ Initial contract owner; receives upgrade authority. function initialize(address owner_) external initializer { if (owner_ == address(0)) revert ZeroOwner(); __Ownable_init(owner_); __UUPSUpgradeable_init(); nextVenueId = 1; } function _authorizeUpgrade(address) internal override onlyOwner {} /// @notice Register a new venue. Pass `enabled = false` to stage the venue /// configuration before going live. Pass `IVenuePolicy(address(0))` /// for `policy` to register without one — a policy can still be /// attached or changed later via `setPolicy`. /// @param feeRecipient Address that receives the routing fee skimmed on each trade; required when any fee > 0. /// @param signer Address whose signatures are checked for gated operations; required when any sig flag is set. /// @param venueFeeBps Fee charged on buy/sell investment amounts in bps (1e4 = 100%); capped at `MAX_VENUE_FEE_BPS`. /// @param marketFeeBps Fee charged as a market-attribution fee in bps; capped at `MAX_VENUE_FEE_BPS`. /// @param requiresCreateSig True if market creation must carry a valid EIP-712 venue signature. /// @param requiresTradeSig True if buy/sell calls must carry a valid EIP-712 venue signature. /// @param enabled Whether this venue is active; disabled venues cannot be used for routing. /// @param policy Optional IVenuePolicy hook contract; pass address(0) for none. /// @return venueId Auto-incrementing ID assigned to the new venue (always >= 1). function register( address feeRecipient, address signer, uint16 venueFeeBps, uint16 marketFeeBps, bool requiresCreateSig, bool requiresTradeSig, bool enabled, IVenuePolicy policy ) external returns (uint32 venueId) { if (venueFeeBps > MAX_VENUE_FEE_BPS) revert VenueFeeTooHigh(); if (marketFeeBps > MAX_VENUE_FEE_BPS) revert VenueFeeTooHigh(); if ((venueFeeBps > 0 || marketFeeBps > 0) && feeRecipient == address(0)) revert FeeRecipientRequired(); if ((requiresCreateSig || requiresTradeSig) && signer == address(0)) revert SignerRequired(); _validatePolicy(policy); venueId = nextVenueId++; _venues[venueId] = Venue({ owner: msg.sender, feeRecipient: feeRecipient, signer: signer, venueFeeBps: venueFeeBps, requiresCreateSig: requiresCreateSig, requiresTradeSig: requiresTradeSig, enabled: enabled, policy: policy, marketFeeBps: marketFeeBps }); emit VenueRegistered( venueId, msg.sender, feeRecipient, signer, venueFeeBps, marketFeeBps, requiresCreateSig, requiresTradeSig, enabled, address(policy) ); } /// @notice Update all mutable fields of a venue in one call. Only the venue owner may call this. /// Same parameter semantics as `register`; see that function for field documentation. function updateVenue( uint32 venueId, address feeRecipient, address signer, uint16 venueFeeBps, uint16 marketFeeBps, bool requiresCreateSig, bool requiresTradeSig, bool enabled, IVenuePolicy policy ) external { Venue storage v = _onlyVenueOwner(venueId); if (venueFeeBps > MAX_VENUE_FEE_BPS) revert VenueFeeTooHigh(); if (marketFeeBps > MAX_VENUE_FEE_BPS) revert VenueFeeTooHigh(); if ((venueFeeBps > 0 || marketFeeBps > 0) && feeRecipient == address(0)) revert FeeRecipientRequired(); if ((requiresCreateSig || requiresTradeSig) && signer == address(0)) revert SignerRequired(); _validatePolicy(policy); v.feeRecipient = feeRecipient; v.signer = signer; v.venueFeeBps = venueFeeBps; v.marketFeeBps = marketFeeBps; v.requiresCreateSig = requiresCreateSig; v.requiresTradeSig = requiresTradeSig; v.enabled = enabled; v.policy = policy; emit VenueUpdated( venueId, feeRecipient, signer, venueFeeBps, marketFeeBps, requiresCreateSig, requiresTradeSig, enabled, address(policy) ); } /// @notice Flip a venue's enabled flag without touching any other field. /// @param venueId Target venue; caller must be its owner. /// @param enabled New enabled state. function setEnabled(uint32 venueId, bool enabled) external { Venue storage v = _onlyVenueOwner(venueId); v.enabled = enabled; emit VenueEnabledChanged(venueId, enabled); } /// @notice Set or clear the access-control policy for a venue. Pass /// `address(0)` to remove the policy (and disable all three policy /// hooks for this venue). /// @param venueId Target venue; caller must be its owner. /// @param policy New IVenuePolicy contract; address(0) removes the policy. function setPolicy(uint32 venueId, IVenuePolicy policy) external { _validatePolicy(policy); Venue storage v = _onlyVenueOwner(venueId); v.policy = policy; emit VenuePolicySet(venueId, address(policy)); } /// @notice Stage a two-step ownership transfer. The pending new owner must /// call `acceptOwnership` to complete the transfer. No-ops silently /// if `newOwner` is already the current owner. /// @param venueId Target venue; caller must be its current owner. /// @param newOwner Address of the proposed new owner; must be non-zero. function transferOwnership(uint32 venueId, address newOwner) external { if (newOwner == address(0)) revert ZeroOwner(); Venue storage v = _onlyVenueOwner(venueId); if (newOwner == v.owner) { delete pendingOwner[venueId]; // cancel any pending transfer return; } pendingOwner[venueId] = newOwner; emit VenueOwnershipTransferStarted(venueId, v.owner, newOwner); } /// @notice Complete a pending ownership transfer. Must be called by the /// address that was staged via `transferOwnership`. /// @param venueId Target venue; `msg.sender` must be the pending new owner. function acceptOwnership(uint32 venueId) external { address pending = pendingOwner[venueId]; if (msg.sender != pending) revert PendingOwnerOnly(); Venue storage v = _venues[venueId]; address old = v.owner; v.owner = msg.sender; delete pendingOwner[venueId]; emit VenueOwnershipTransferred(venueId, old, msg.sender); } /// @dev Revert if `policy` is non-zero but does not declare ERC-165 support /// for IVenuePolicy. Catches both revert and false-return cases. function _validatePolicy(IVenuePolicy policy) internal view { if (address(policy) == address(0)) return; try policy.supportsInterface(type(IVenuePolicy).interfaceId) returns (bool ok) { if (!ok) revert InvalidPolicy(); } catch { revert InvalidPolicy(); } } uint256[47] private __gap; /// @dev Load the venue and assert the caller is its owner. Returns the /// storage pointer so callers can mutate fields without a second SLOAD. function _onlyVenueOwner(uint32 venueId) internal view returns (Venue storage v) { v = _venues[venueId]; if (v.owner == address(0)) revert UnknownVenue(); if (msg.sender != v.owner) revert NotOwner(); } // ---- Views ----------------------------------------------------------- /// @notice Return all fields for a venue. Reverts for the reserved ID 0. /// @param venueId Target venue. /// @return Full Venue struct; owner is zero for unregistered IDs. function getVenue(uint32 venueId) external view returns (Venue memory) { if (venueId == 0) revert VenueIdReserved(); return _venues[venueId]; } /// @notice Returns the access-control policy attached to `venueId`, or /// `address(0)` if none is set. Reading the policy alone (instead of /// the whole `Venue` struct) keeps the router's hot path lean. /// @param venueId Target venue; 0 reverts with VenueIdReserved. /// @return The attached IVenuePolicy, or address(0) if not set. function policyOf(uint32 venueId) external view returns (IVenuePolicy) { if (venueId == 0) revert VenueIdReserved(); return _venues[venueId].policy; } /// @notice Returns all routing-relevant fields plus the policy in a single call. /// Reverts if the venue is unknown or disabled. /// @param venueId Target venue. /// @return feeRecipient Address that receives the routing fee. /// @return signer Address whose signatures are verified on gated operations. /// @return venueFeeBps Routing fee in bps. /// @return requiresCreateSig True if market-creation calls must be signed. /// @return requiresTradeSig True if buy/sell calls must be signed. /// @return policy Attached IVenuePolicy, or address(0) if none. function venueForRoutingFull(uint32 venueId) external view returns ( address feeRecipient, address signer, uint16 venueFeeBps, bool requiresCreateSig, bool requiresTradeSig, IVenuePolicy policy ) { Venue storage v = _venues[venueId]; if (v.owner == address(0)) revert UnknownVenue(); if (!v.enabled) revert VenueDisabled(); return (v.feeRecipient, v.signer, v.venueFeeBps, v.requiresCreateSig, v.requiresTradeSig, v.policy); } /// @notice Returns the three fields the Core needs for the market-venue fee tier /// in a single SLOAD path. venueId==0 returns zero/null values so the /// caller can unconditionally invoke this without pre-checking. /// @param venueId Target venue; 0 or disabled venues return zero values without reverting. /// @return feeRecipient Address that receives the market-attribution fee. /// @return marketFeeBps Market-attribution fee in bps. /// @return policy Attached IVenuePolicy, or address(0) if none. function marketFeeInfoFull(uint32 venueId) external view returns (address feeRecipient, uint16 marketFeeBps, IVenuePolicy policy) { if (venueId == 0) return (address(0), 0, IVenuePolicy(address(0))); Venue storage v = _venues[venueId]; if (!v.enabled) return (address(0), 0, IVenuePolicy(address(0))); return (v.feeRecipient, v.marketFeeBps, v.policy); } }lib/openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol) pragma solidity ^0.8.20; import {OwnableUpgradeable} from "./OwnableUpgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This extension of the {Ownable} contract includes a two-step mechanism to transfer * ownership, where the new owner must call {acceptOwnership} in order to replace the * old one. This can help prevent common mistakes, such as transfers of ownership to * incorrect accounts, or to contracts that are unable to interact with the * permission system. * * The initial owner is specified at deployment time in the constructor for `Ownable`. This * can later be changed with {transferOwnership} and {acceptOwnership}. * * This module is used through inheritance. It will make available all functions * from parent (Ownable). */ abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable { /// @custom:storage-location erc7201:openzeppelin.storage.Ownable2Step struct Ownable2StepStorage { address _pendingOwner; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable2Step")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant Ownable2StepStorageLocation = 0x237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00; function _getOwnable2StepStorage() private pure returns (Ownable2StepStorage storage $) { assembly { $.slot := Ownable2StepStorageLocation } } event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner); function __Ownable2Step_init() internal onlyInitializing { } function __Ownable2Step_init_unchained() internal onlyInitializing { } /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view virtual returns (address) { Ownable2StepStorage storage $ = _getOwnable2StepStorage(); return $._pendingOwner; } /** * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. * Can only be called by the current owner. * * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer. */ function transferOwnership(address newOwner) public virtual override onlyOwner { Ownable2StepStorage storage $ = _getOwnable2StepStorage(); $._pendingOwner = newOwner; emit OwnershipTransferStarted(owner(), newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner. * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual override { Ownable2StepStorage storage $ = _getOwnable2StepStorage(); delete $._pendingOwner; super._transferOwnership(newOwner); } /** * @dev The new owner accepts the ownership transfer. */ function acceptOwnership() public virtual { address sender = _msgSender(); if (pendingOwner() != sender) { revert OwnableUnauthorizedAccount(sender); } _transferOwnership(sender); } }lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol) pragma solidity ^0.8.20; import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * The initial owner is set to the address provided by the deployer. This can * later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { /// @custom:storage-location erc7201:openzeppelin.storage.Ownable struct OwnableStorage { address _owner; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300; function _getOwnableStorage() private pure returns (OwnableStorage storage $) { assembly { $.slot := OwnableStorageLocation } } /** * @dev The caller account is not authorized to perform an operation. */ error OwnableUnauthorizedAccount(address account); /** * @dev The owner is not a valid owner account. (eg. `address(0)`) */ error OwnableInvalidOwner(address owner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the address provided by the deployer as the initial owner. */ function __Ownable_init(address initialOwner) internal onlyInitializing { __Ownable_init_unchained(initialOwner); } function __Ownable_init_unchained(address initialOwner) internal onlyInitializing { if (initialOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(initialOwner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { OwnableStorage storage $ = _getOwnableStorage(); return $._owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { if (owner() != _msgSender()) { revert OwnableUnauthorizedAccount(_msgSender()); } } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { if (newOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { OwnableStorage storage $ = _getOwnableStorage(); address oldOwner = $._owner; $._owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }src/interfaces/IOracleAnswerReceiver.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// @title IOracleAnswerReceiver /// @notice Implemented by the router. Called by oracle adapters when a question /// has been answered. Only the adapter registered for a given market may /// call this. /// /// Implements ERC-165 so adapters can verify the receiver at construction /// time rather than discovering a misconfiguration at resolution time. interface IOracleAnswerReceiver is IERC165 { /// @notice Notify the router that an oracle question has been answered. /// Called by the registered adapter for the market bound to `oracleQuestionId`. function onOracleAnswer(uint256 oracleQuestionId, uint8 outcomeIdx, bool voided) external; }lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) pragma solidity ^0.8.20; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } }lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol) pragma solidity ^0.8.20; /** * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC. */ interface IERC1967 { /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Emitted when the beacon is changed. */ event BeaconUpgraded(address indexed beacon); }lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/Strings.sol) pragma solidity ^0.8.20; import {Math} from "./math/Math.sol"; import {SignedMath} from "./math/SignedMath.sol"; /** * @dev String operations. */ library Strings { bytes16 private constant HEX_DIGITS = "0123456789abcdef"; uint8 private constant ADDRESS_LENGTH = 20; /** * @dev The `value` string doesn't fit in the specified `length`. */ error StringsInsufficientHexLength(uint256 value, uint256 length); /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = Math.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; assembly ("memory-safe") { ptr := add(buffer, add(32, length)) } while (true) { ptr--; assembly ("memory-safe") { mstore8(ptr, byte(mod(value, 10), HEX_DIGITS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toStringSigned(int256 value) internal pure returns (string memory) { return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, Math.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { uint256 localValue = value; bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = HEX_DIGITS[localValue & 0xf]; localValue >>= 4; } if (localValue != 0) { revert StringsInsufficientHexLength(value, length); } return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal * representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH); } /** * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal * representation, according to EIP-55. */ function toChecksumHexString(address addr) internal pure returns (string memory) { bytes memory buffer = bytes(toHexString(addr)); // hash the hex part of buffer (skip length + 2 bytes, length 40) uint256 hashValue; assembly ("memory-safe") { hashValue := shr(96, keccak256(add(buffer, 0x22), 40)) } for (uint256 i = 41; i > 1; --i) { // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f) if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) { // case shift by xoring with 0x20 buffer[i] ^= 0x20; } hashValue >>= 4; } return string(buffer); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b)); } }src/interfaces/IOracleAdapter.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {QuestionDefinition} from "../types/OracleTypes.sol"; /// @title IOracleAdapter /// @notice Interface that oracle adapters must implement. Each adapter normalises a /// specific oracle's interface into a standard surface the router can call. /// The adapter also owns the Somnia reactivity subscription for its oracle /// and calls `IOracleAnswerReceiver.onOracleAnswer` when an answer is posted. /// /// Implements ERC-165. The router validates `supportsInterface` at market /// creation, so passing a non-conforming address reverts. interface IOracleAdapter is IERC165 { /// @notice Returns the number of outcome slots for a given oracle question. /// Called by the router at market creation to determine outcomeSlotCount. function getSlotCount(uint256 oracleQuestionId) external view returns (uint8); /// @notice Pulls the current answer from the oracle. Used as the pull-fallback /// path (replaces the router reading the oracle directly in pokeOracle). /// Must revert if no answer is available yet. function pullAnswer(uint256 oracleQuestionId) external view returns (uint8 outcomeIdx, bool voided); /// @notice Schedules a new oracle question. Optional — adapters that do not /// support scheduling should revert on this call. function scheduleQuestion(QuestionDefinition calldata def) external payable returns (uint256 oracleQuestionId); /// @notice Returns the cost in native token to schedule a question. /// Returns 0 if scheduling is not supported by this adapter. function getSchedulingCost(QuestionDefinition calldata def) external view returns (uint256); }lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.20; import {SafeCast} from "./SafeCast.sol"; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMath { /** * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant. * * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone. * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute * one branch when needed, making this function more expensive. */ function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) { unchecked { // branchless ternary works because: // b ^ (a ^ b) == a // b ^ 0 == b return b ^ ((a ^ b) * int256(SafeCast.toUint(condition))); } } /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return ternary(a > b, a, b); } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return ternary(a < b, a, b); } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson. // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift, // taking advantage of the most significant (or "sign" bit) in two's complement representation. // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result, // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative). int256 mask = n >> 255; // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it. return uint256((n + mask) ^ mask); } } }src/FixedProductMarketMaker.sol
// SPDX-License-Identifier: LGPL-3.0 pragma solidity ^0.8.20; import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {ERC1155HolderUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol"; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {ConditionalTokens} from "./ConditionalTokens.sol"; import {CTHelpers} from "./CTHelpers.sol"; /// @title FixedProductMarketMaker /// @notice Per-market constant-product AMM. Deployed as a minimal proxy clone /// for each market. LP shares are ERC-20. Same math as ConditionalCPMM. contract FixedProductMarketMaker is Initializable, ERC20Upgradeable, ERC1155HolderUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; error NotRouter(); error InvalidConditionSetup(); error InvalidTradingWindow(); error InvalidDistributionHint(); error InvalidOutcomeIndex(); error InvalidIndexSet(); error MinAmountNotReached(); error MaxAmountExceeded(); error EmptyPool(); error FundingMustBePositive(); error NotOpenYet(); error TradingClosed(); error NotActivator(); error TradingAlreadyOpen(); error TradingStartTooFar(); error UnsupportedIndexSetBitcount(); uint256 internal constant ONE = 1e18; uint256 internal constant MINIMUM_LIQUIDITY = 1000; uint64 public constant MAX_TRADING_START_DELAY = 30 days; ConditionalTokens public conditionalTokens; IERC20 public collateralToken; bytes32 public conditionId; uint8 public outcomeSlotCount; uint64 public tradingStart; uint64 public tradingClose; address public activator; uint256 public fee; address public router; uint256 public feePoolWeight; mapping(address => uint256) internal withdrawnFees; mapping(address => uint256) internal claimableFees; uint256[] internal _positionIds; event TradingStartUpdated(bytes32 indexed conditionId_, uint64 newTradingStart); event FundingAdded( bytes32 indexed conditionId_, address indexed funder, uint256[] amountsAdded, uint256 sharesMinted ); event FundingRemoved( bytes32 indexed conditionId_, address indexed funder, uint256[] amountsRemoved, uint256 collateralRemovedFromFeePool, uint256 sharesBurnt ); event Buy( bytes32 indexed conditionId_, address indexed buyer, uint256 indexed indexSet, uint256 investmentAmount, uint256 feeAmount, uint256 outcomeTokensBought ); event Sell( bytes32 indexed conditionId_, address indexed seller, uint256 indexed outcomeIndex, uint256 returnAmount, uint256 feeAmount, uint256 outcomeTokensSold ); event FeesWithdrawn(bytes32 indexed conditionId_, address indexed account, uint256 amount); event FeesAccrued(bytes32 indexed conditionId_, address indexed account, uint256 amount); /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } /// @notice Initialises the FPMM clone. Called once by the factory immediately after deployment. /// @param _ct ConditionalTokens contract that holds the outcome positions. /// @param _conditionId Condition whose outcomes this market trades. /// @param _collateralToken ERC-20 used as collateral for all trades and liquidity. /// @param _fee Trading fee in WAD (1e18 = 100%); must be less than 1e18. /// @param _tradingStart Unix timestamp when trading opens; 0 means open immediately. /// @param _tradingClose Unix timestamp when trading closes; 0 means no close time. /// @param _activator Address permitted to call `setTradingStart`. /// @param _router OrderRouter address; all mutating calls must originate from here. function initialize( ConditionalTokens _ct, bytes32 _conditionId, IERC20 _collateralToken, uint256 _fee, uint64 _tradingStart, uint64 _tradingClose, address _activator, address _router ) external initializer { __ERC20_init("FPM Shares", "FPMM"); __ERC1155Holder_init(); __ReentrancyGuard_init(); uint256 slots = _ct.getOutcomeSlotCount(_conditionId); if (slots < 2) revert InvalidConditionSetup(); if (_fee >= ONE) revert InvalidConditionSetup(); if (_tradingStart != 0 && _tradingClose != 0 && _tradingClose <= _tradingStart) { revert InvalidTradingWindow(); } conditionalTokens = _ct; conditionId = _conditionId; collateralToken = _collateralToken; outcomeSlotCount = uint8(slots); tradingStart = _tradingStart; tradingClose = _tradingClose; activator = _activator; fee = _fee; router = _router; uint256[] memory ids = new uint256[](slots); for (uint256 i = 0; i < slots; i++) { ids[i] = CTHelpers.getPositionId( _collateralToken, CTHelpers.getCollectionId(bytes32(0), _conditionId, uint256(1) << i) ); } _positionIds = ids; } modifier onlyRouter() { if (msg.sender != router) revert NotRouter(); _; } // ---- view helpers ---------------------------------------------------- /// @notice Returns the ERC-1155 position IDs for each outcome slot in order. /// @return The array of position IDs; index i corresponds to outcome slot i. function positionIds() external view returns (uint256[] memory) { return _positionIds; } /// @notice Returns a snapshot of the key pool configuration values. /// @return collateralToken_ ERC-20 token used as collateral. /// @return outcomeSlotCount_ Number of outcome slots in this market. /// @return tradingStart_ Unix timestamp when trading opens (0 = open immediately). /// @return tradingClose_ Unix timestamp when trading closes (0 = no close). /// @return fee_ Trading fee in WAD (1e18 = 100%). /// @return feePoolWeight_ Cumulative LP fee pool used for pro-rata fee accounting. function poolInfo() external view returns ( IERC20 collateralToken_, uint8 outcomeSlotCount_, uint64 tradingStart_, uint64 tradingClose_, uint256 fee_, uint256 feePoolWeight_ ) { return (collateralToken, outcomeSlotCount, tradingStart, tradingClose, fee, feePoolWeight); } /// @notice Returns the FPMM's current balance of each outcome token. /// @return Outcome token balances, indexed by outcome slot. function getPoolBalances() public view returns (uint256[] memory) { uint256 n = _positionIds.length; address[] memory thisAddrs = new address[](n); uint256[] memory idsCopy = new uint256[](n); for (uint256 i = 0; i < n; i++) { thisAddrs[i] = address(this); idsCopy[i] = _positionIds[i]; } return IERC1155(address(conditionalTokens)).balanceOfBatch(thisAddrs, idsCopy); } // ---- fee accounting ------------------------------------------------- /// @notice Returns the total collateral currently claimable as fees by `account`. /// @param account Address of the LP to query. /// @return Total withdrawable fee amount in collateral token units. function feesWithdrawableBy(address account) public view returns (uint256) { uint256 supply = totalSupply(); uint256 pending = 0; if (supply > 0) { uint256 raw = (feePoolWeight * balanceOf(account)) / supply; uint256 withdrawn = withdrawnFees[account]; if (raw > withdrawn) pending = raw - withdrawn; } return pending + claimableFees[account]; } function _creditFees(address account) internal { uint256 supply = totalSupply(); if (supply == 0) return; uint256 raw = (feePoolWeight * balanceOf(account)) / supply; uint256 withdrawn = withdrawnFees[account]; if (raw > withdrawn) { uint256 amount = raw - withdrawn; withdrawnFees[account] = raw; claimableFees[account] += amount; emit FeesAccrued(conditionId, account, amount); } } /// @notice Credits any pending fees for `account` then transfers them to the /// router (msg.sender). The router forwards the collateral through /// PredictionMarketCore, which is the single exit point for collateral /// to users — fees never leave a market clone directly. /// @param account Address whose accrued fees are settled. /// @return claimable Amount transferred to the router. function withdrawFees(address account) public onlyRouter returns (uint256 claimable) { _creditFees(account); claimable = claimableFees[account]; if (claimable > 0) { claimableFees[account] = 0; collateralToken.safeTransfer(msg.sender, claimable); emit FeesWithdrawn(conditionId, account, claimable); } } /// @dev ERC-20 _update hook: applies fee accounting before the balance mutation. /// Called on every mint, burn, and transfer. function _update(address from, address to, uint256 value) internal override { if (from != address(0)) _creditFees(from); uint256 supply = totalSupply(); uint256 withdrawnFeesTransfer = supply == 0 ? value : (feePoolWeight * value) / supply; if (from != address(0)) { withdrawnFees[from] -= withdrawnFeesTransfer; } else { feePoolWeight += withdrawnFeesTransfer; } if (to != address(0)) { withdrawnFees[to] += withdrawnFeesTransfer; } else { feePoolWeight -= withdrawnFeesTransfer; } super._update(from, to, value); } // ---- setTradingStart ------------------------------------------------ /// @notice Updates the trading-open timestamp. Only the activator may call this via the router. /// @param newTradingStart New Unix timestamp for when trading opens; 0 resets to open immediately. /// @param claimedActivator Address that must match the stored `activator`; used to authenticate the caller. function setTradingStart(uint64 newTradingStart, address claimedActivator) external onlyRouter { if (claimedActivator != activator) revert NotActivator(); if (newTradingStart != 0) { if (tradingStart == 0 || block.timestamp >= tradingStart) revert TradingAlreadyOpen(); if (newTradingStart > uint64(block.timestamp) + MAX_TRADING_START_DELAY) revert TradingStartTooFar(); if (tradingClose != 0 && newTradingStart >= tradingClose) revert InvalidTradingWindow(); } tradingStart = newTradingStart; emit TradingStartUpdated(conditionId, newTradingStart); } // ---- liquidity ------------------------------------------------------- /// @notice Adds liquidity to the pool and mints LP shares to the caller (the router). /// @param addedFunds Amount of collateral token to deposit; must be greater than zero. /// @param distributionHint Proportional target balances for each outcome on the first deposit; /// must have one entry per outcome with no zero values. Pass an empty /// array on subsequent deposits (uniform top-up follows pool ratios). /// @return mintAmount Number of LP shares minted to the caller. function addFunding(uint256 addedFunds, uint256[] calldata distributionHint) external onlyRouter nonReentrant returns (uint256 mintAmount) { if (addedFunds == 0) revert FundingMustBePositive(); uint256[] memory poolBalances = getPoolBalances(); uint256 n = poolBalances.length; uint256[] memory sendBackAmounts = new uint256[](n); uint256 supply = totalSupply(); if (supply == 0) { if (distributionHint.length != n) revert InvalidDistributionHint(); uint256 maxHint; for (uint256 i = 0; i < n; i++) { if (distributionHint[i] == 0) revert InvalidDistributionHint(); if (distributionHint[i] > maxHint) maxHint = distributionHint[i]; } for (uint256 i = 0; i < n; i++) { uint256 remaining = (addedFunds * distributionHint[i]) / maxHint; sendBackAmounts[i] = addedFunds - remaining; } mintAmount = addedFunds; _mint(address(0xdead), MINIMUM_LIQUIDITY); mintAmount -= MINIMUM_LIQUIDITY; } else { if (distributionHint.length != 0) revert InvalidDistributionHint(); uint256 poolWeight; for (uint256 i = 0; i < n; i++) { if (poolBalances[i] > poolWeight) poolWeight = poolBalances[i]; } for (uint256 i = 0; i < n; i++) { uint256 remaining = (addedFunds * poolBalances[i]) / poolWeight; sendBackAmounts[i] = addedFunds - remaining; } mintAmount = (addedFunds * supply) / poolWeight; if (mintAmount == 0) revert FundingMustBePositive(); } collateralToken.safeTransferFrom(msg.sender, address(this), addedFunds); collateralToken.forceApprove(address(conditionalTokens), addedFunds); _splitPositionThroughCondition(addedFunds); _mint(msg.sender, mintAmount); IERC1155(address(conditionalTokens)).safeBatchTransferFrom( address(this), msg.sender, _positionIds, sendBackAmounts, "" ); emit FundingAdded(conditionId, msg.sender, sendBackAmounts, mintAmount); } /// @notice Remove liquidity. `account` is the original LP whose fee credit is /// settled atomically here, before _burn, so share-balance changes don't /// affect the credit calculation. /// @param sharesToBurn Number of LP shares to burn; determines the pro-rata outcome tokens returned. /// @param account Original LP address whose accrued fees are settled before the burn. function removeFunding(uint256 sharesToBurn, address account) external onlyRouter nonReentrant { // Settle any accrued fees for the LP before burning their shares. _creditFees(account); uint256[] memory poolBalances = getPoolBalances(); uint256 supply = totalSupply(); uint256 n = poolBalances.length; uint256[] memory sendAmounts = new uint256[](n); for (uint256 i = 0; i < n; i++) { sendAmounts[i] = (poolBalances[i] * sharesToBurn) / supply; } uint256 collateralBefore = collateralToken.balanceOf(address(this)); _burn(msg.sender, sharesToBurn); uint256 collateralRemovedFromFeePool = collateralBefore - collateralToken.balanceOf(address(this)); IERC1155(address(conditionalTokens)).safeBatchTransferFrom( address(this), msg.sender, _positionIds, sendAmounts, "" ); emit FundingRemoved(conditionId, msg.sender, sendAmounts, collateralRemovedFromFeePool, sharesToBurn); } // ---- trade math ------------------------------------------------------ /// @notice Computes how many outcome tokens the buyer receives for a given collateral investment. /// @param investmentAmount Gross collateral amount the buyer pays (fee is deducted inside). /// @param indexSet Bitmask of outcome slots being purchased (bit i set = outcome i included). /// Supports single-outcome (1 bit), two-outcome (2 bits), and full-bundle /// (all bits set) purchases. /// @return amountPerOutcome Number of tokens received per selected outcome. function calcBuyAmount(uint256 investmentAmount, uint256 indexSet) public view returns (uint256 amountPerOutcome) { uint256 n = _positionIds.length; if (indexSet == 0 || indexSet >> n != 0) revert InvalidIndexSet(); uint256[] memory bal = getPoolBalances(); uint256 I = investmentAmount - (investmentAmount * fee) / ONE; uint256 bits = _popcount(indexSet); if (bits == 1) { uint256 k = _lsb(indexSet); uint256 endingBal = bal[k] * ONE; for (uint256 i = 0; i < n; i++) { if (i != k) endingBal = endingBal * bal[i] / (bal[i] + I); } if (endingBal == 0) revert EmptyPool(); return bal[k] + I - _ceildiv(endingBal, ONE); } if (bits == 2) { uint256 a = _lsb(indexSet); uint256 b = _lsb(indexSet ^ (uint256(1) << a)); uint256 Aa = bal[a] + I; uint256 Ab = bal[b] + I; uint256 P = ONE; for (uint256 i = 0; i < n; i++) { uint256 Ai = bal[i] + I; P = (P * bal[i] + Ai - 1) / Ai; } if (P == 0) revert EmptyPool(); uint256 K = (Aa * Ab * P + ONE - 1) / ONE; uint256 diff = Aa >= Ab ? Aa - Ab : Ab - Aa; uint256 disc = diff * diff + 4 * K; uint256 sqrtDisc = Math.sqrt(disc); if (sqrtDisc * sqrtDisc < disc) sqrtDisc++; uint256 sumAB = Aa + Ab; if (sqrtDisc >= sumAB) revert EmptyPool(); return (sumAB - sqrtDisc) / 2; } // Full bundle: all outcomes, returns investment minus fee. if (bits == n) return I; revert UnsupportedIndexSetBitcount(); } /// @notice Computes how many outcome tokens the seller must provide to receive `returnAmount` collateral. /// @param returnAmount Net collateral the seller wants to receive (fee is added on top). /// @param outcomeIndex Zero-based index of the single outcome being sold. /// @return Number of outcome tokens the seller must supply. function calcSellAmount(uint256 returnAmount, uint256 outcomeIndex) public view returns (uint256) { if (outcomeIndex >= _positionIds.length) revert InvalidOutcomeIndex(); uint256[] memory poolBalances = getPoolBalances(); uint256 returnAmountPlusFees = (returnAmount * ONE) / (ONE - fee); uint256 sellTokenPoolBalance = poolBalances[outcomeIndex]; uint256 endingOutcomeBalance = sellTokenPoolBalance * ONE; for (uint256 i = 0; i < poolBalances.length; i++) { if (i != outcomeIndex) { uint256 poolBalance = poolBalances[i]; if (returnAmountPlusFees >= poolBalance) revert EmptyPool(); endingOutcomeBalance = (endingOutcomeBalance * poolBalance) / (poolBalance - returnAmountPlusFees); } } if (endingOutcomeBalance == 0) revert EmptyPool(); return returnAmountPlusFees + _ceildiv(endingOutcomeBalance, ONE) - sellTokenPoolBalance; } // ---- trading --------------------------------------------------------- function _onlyTradingOpen() internal view { if (tradingStart != 0 && block.timestamp < tradingStart) revert NotOpenYet(); if (tradingClose != 0 && block.timestamp >= tradingClose) revert TradingClosed(); } /// @notice Executes a buy trade: transfers collateral from the router, deducts the fee, and /// delivers outcome tokens for the selected index set to the router. /// @param investmentAmount Gross collateral amount to invest (inclusive of fee). /// @param indexSet Bitmask of outcome slots being purchased. /// @param minOutcomeTokensToBuy Slippage guard; reverts if fewer tokens would be received. /// @return outcomeTokensBought Number of outcome tokens delivered per selected outcome. function buy(uint256 investmentAmount, uint256 indexSet, uint256 minOutcomeTokensToBuy) external onlyRouter nonReentrant returns (uint256 outcomeTokensBought) { _onlyTradingOpen(); outcomeTokensBought = calcBuyAmount(investmentAmount, indexSet); if (outcomeTokensBought < minOutcomeTokensToBuy) revert MinAmountNotReached(); collateralToken.safeTransferFrom(msg.sender, address(this), investmentAmount); uint256 feeAmount = (investmentAmount * fee) / ONE; feePoolWeight += feeAmount; uint256 investmentAmountMinusFees = investmentAmount - feeAmount; collateralToken.forceApprove(address(conditionalTokens), investmentAmountMinusFees); _splitPositionThroughCondition(investmentAmountMinusFees); _transferOutcomeTokens(indexSet, outcomeTokensBought, msg.sender); emit Buy(conditionId, msg.sender, indexSet, investmentAmount, feeAmount, outcomeTokensBought); } /// @notice Sell outcome tokens. The caller (OrderRouter) pre-computes /// `exactOutcomeTokensSold` via `calcSellAmount` and passes it here /// to avoid a redundant on-chain calculation. /// @param returnAmount Net collateral the seller receives (fee is charged on top). /// @param outcomeIndex Zero-based index of the outcome token being sold. /// @param maxOutcomeTokensToSell Slippage guard; reverts if more tokens would be required. /// @param exactOutcomeTokensSold Pre-computed token input amount from `calcSellAmount`. /// @return outcomeTokensSold Number of outcome tokens actually consumed (equals `exactOutcomeTokensSold`). function sell(uint256 returnAmount, uint256 outcomeIndex, uint256 maxOutcomeTokensToSell, uint256 exactOutcomeTokensSold) external onlyRouter nonReentrant returns (uint256 outcomeTokensSold) { _onlyTradingOpen(); outcomeTokensSold = exactOutcomeTokensSold; if (outcomeTokensSold > maxOutcomeTokensToSell) revert MaxAmountExceeded(); IERC1155(address(conditionalTokens)).safeTransferFrom( msg.sender, address(this), _positionIds[outcomeIndex], outcomeTokensSold, "" ); uint256 feeAmount = (returnAmount * fee) / (ONE - fee); feePoolWeight += feeAmount; uint256 returnAmountPlusFees = returnAmount + feeAmount; _mergePositionsThroughCondition(returnAmountPlusFees); collateralToken.safeTransfer(msg.sender, returnAmount); emit Sell(conditionId, msg.sender, outcomeIndex, returnAmount, feeAmount, outcomeTokensSold); } // ---- internal helpers ------------------------------------------------ function _splitPositionThroughCondition(uint256 amount) internal { conditionalTokens.splitPosition( collateralToken, bytes32(0), conditionId, CTHelpers.buildSlotPartition(outcomeSlotCount), amount ); } function _mergePositionsThroughCondition(uint256 amount) internal { conditionalTokens.mergePositions( collateralToken, bytes32(0), conditionId, CTHelpers.buildSlotPartition(outcomeSlotCount), amount ); } function _ceildiv(uint256 x, uint256 y) internal pure returns (uint256) { return (x + y - 1) / y; } function _popcount(uint256 x) internal pure returns (uint256 n) { while (x != 0) { unchecked { n += x & 1; x >>= 1; } } } function _lsb(uint256 x) internal pure returns (uint256 i) { if (x == 0) revert InvalidIndexSet(); while ((x >> i) & 1 == 0) { unchecked { i++; } } } function _transferOutcomeTokens(uint256 indexSet, uint256 amount, address to) internal { uint256 n = _positionIds.length; uint256 bits = _popcount(indexSet); if (bits == 1) { IERC1155(address(conditionalTokens)).safeTransferFrom( address(this), to, _positionIds[_lsb(indexSet)], amount, "" ); } else { uint256[] memory outIds = new uint256[](bits); uint256[] memory amounts = new uint256[](bits); uint256 j = 0; for (uint256 i = 0; i < n; i++) { if (indexSet >> i & 1 != 0) { outIds[j] = _positionIds[i]; amounts[j] = amount; unchecked { j++; } } } IERC1155(address(conditionalTokens)).safeBatchTransferFrom(address(this), to, outIds, amounts, ""); } } // ---- interface plumbing --------------------------------------------- /// @notice Returns true if the contract implements `interfaceId` per ERC-165. /// @param interfaceId The interface identifier to check. /// @return True if the interface is supported. function supportsInterface(bytes4 interfaceId) public view override(ERC1155HolderUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } uint256[39] private __gap; }lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) pragma solidity ^0.8.20; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } }lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol) pragma solidity ^0.8.20; interface IERC5267 { /** * @dev MAY be emitted to signal that the domain could have changed. */ event EIP712DomainChanged(); /** * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712 * signature. */ function eip712Domain() external view returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ); }src/CTHelpers.sol
// SPDX-License-Identifier: LGPL-3.0 pragma solidity ^0.8.20; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title CTHelpers /// @notice Pure ID derivation for ConditionalTokens. /// @dev Modernized port of Gnosis CTHelpers. The hierarchical collection-id /// derivation has been simplified to a plain keccak256 chain; the /// original used an alt_bn128 point-addition trick to make union of /// conditions canonical (e.g. nesting A under B vs B under A produced /// the same id). We don't need that property for single-condition /// prediction markets, which is the only nesting the factory exposes. library CTHelpers { /// @notice Hash an oracle, question id, and outcome slot count into the /// canonical condition id. The oracle is hashed in, so only that /// address can later call `reportPayouts` for the condition. /// @param oracle Address authorized to report payouts. /// @param questionId Opaque identifier (oracle-specific meaning). /// @param outcomeSlotCount Number of mutually-exclusive outcomes. /// @return conditionId `keccak256(oracle, questionId, outcomeSlotCount)`. function getConditionId(address oracle, bytes32 questionId, uint256 outcomeSlotCount) internal pure returns (bytes32 conditionId) { assembly { let ptr := mload(0x40) mstore(ptr, shl(96, oracle)) mstore(add(ptr, 0x14), questionId) mstore(add(ptr, 0x34), outcomeSlotCount) conditionId := keccak256(ptr, 0x54) } } /// @notice Hash a parent collection, condition, and index set into a child /// collection id. `parentCollectionId == bytes32(0)` denotes the /// root (collateral) collection, which uses a different preimage /// shape so root collections don't collide with nested ones. /// @param parentCollectionId `bytes32(0)` for the root collection. /// @param conditionId The condition under which to derive. /// @param indexSet Bitmask of outcome slots making up this collection. function getCollectionId(bytes32 parentCollectionId, bytes32 conditionId, uint256 indexSet) internal pure returns (bytes32 collectionId) { if (parentCollectionId == bytes32(0)) { assembly { let ptr := mload(0x40) mstore(ptr, conditionId) mstore(add(ptr, 0x20), indexSet) collectionId := keccak256(ptr, 0x40) } } else { assembly { let ptr := mload(0x40) mstore(ptr, parentCollectionId) mstore(add(ptr, 0x20), conditionId) mstore(add(ptr, 0x40), indexSet) collectionId := keccak256(ptr, 0x60) } } } /// @notice Hash a collateral token and collection id into the ERC-1155 /// position id used by `ConditionalTokens`. /// @param collateralToken The collateral asset backing this position. /// @param collectionId The collection (outcome bundle) this position represents. /// @return `uint256(keccak256(collateralToken, collectionId))`. function getPositionId(IERC20 collateralToken, bytes32 collectionId) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(address(collateralToken), collectionId))); } /// @notice Build the canonical per-slot partition `[1, 2, 4, …, 1 << (slots-1)]` /// — one index set per outcome. This is the partition every /// "full set" mint/merge uses. function buildSlotPartition(uint256 slots) internal pure returns (uint256[] memory partition) { partition = new uint256[](slots); for (uint256 i = 0; i < slots; i++) partition[i] = uint256(1) << i; } }src/ConditionalTokens.sol
// SPDX-License-Identifier: LGPL-3.0 pragma solidity ^0.8.20; import {ERC1155} from "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {CTHelpers} from "./CTHelpers.sol"; /// @title ConditionalTokens /// @notice Modernized port of the Gnosis Conditional Tokens Framework /// (https://github.com/gnosis/conditional-tokens-contracts) to /// Solidity 0.8 + OpenZeppelin v5. /// @dev Holds collateral in escrow, mints ERC-1155 outcome tokens per /// condition, and pays out at resolution. The contract is permissionless: /// anyone may prepare a condition by registering an oracle address; only /// that oracle may call `reportPayouts` for it (the binding is enforced /// by hashing the oracle into `conditionId`). contract ConditionalTokens is ERC1155, ReentrancyGuard { using SafeERC20 for IERC20; /// @notice Outcome slot count must be in [2, 256]. error InvalidOutcomeSlotCount(); /// @notice `prepareCondition` called twice for the same `conditionId`. error ConditionAlreadyPrepared(); /// @notice Condition has not been registered via `prepareCondition`. error ConditionNotPrepared(); /// @notice The condition's oracle has already reported payouts. error PayoutsAlreadyReported(); /// @notice Reported payouts sum to zero (no winning outcome). error PayoutIsAllZeroes(); /// @notice Partition is empty, has length 1, or contains overlapping index sets. error InvalidPartition(); /// @notice An index set is zero or refers to a bit beyond `outcomeSlotCount`. error InvalidIndexSet(); /// @notice Redemption attempted before the oracle reported payouts. error ResultNotReceived(); /// @notice Emitted when a new condition is registered. /// @param conditionId Derived id `keccak256(oracle, questionId, outcomeSlotCount)`. /// @param oracle Address authorized to report payouts. /// @param questionId Opaque identifier supplied by the preparer. /// @param outcomeSlotCount Number of mutually-exclusive outcomes. event ConditionPreparation( bytes32 indexed conditionId, address indexed oracle, bytes32 indexed questionId, uint256 outcomeSlotCount ); /// @notice Emitted when the oracle reports the final payout vector. /// @param payoutNumerators Per-slot payout share (sum = denominator). event ConditionResolution( bytes32 indexed conditionId, address indexed oracle, bytes32 indexed questionId, uint256 outcomeSlotCount, uint256[] payoutNumerators ); /// @notice Emitted when collateral / a parent position is split into per-outcome tokens. event PositionSplit( address indexed stakeholder, IERC20 collateralToken, bytes32 indexed parentCollectionId, bytes32 indexed conditionId, uint256[] partition, uint256 amount ); /// @notice Emitted when outcome tokens are merged back into collateral or a parent position. event PositionsMerge( address indexed stakeholder, IERC20 collateralToken, bytes32 indexed parentCollectionId, bytes32 indexed conditionId, uint256[] partition, uint256 amount ); /// @notice Emitted when a holder redeems their outcome tokens against a resolved condition. /// @param payout Total collateral paid out (sum of `stake * numerator / denominator` per index set, floored). event PayoutRedemption( address indexed redeemer, IERC20 indexed collateralToken, bytes32 indexed parentCollectionId, bytes32 conditionId, uint256[] indexSets, uint256 payout ); /// @notice `conditionId` → per-slot payout numerator. Length equals /// `outcomeSlotCount` once the condition has been prepared. mapping(bytes32 => uint256[]) public payoutNumerators; /// @notice `conditionId` → sum of payout numerators. `0` means the /// condition has not been resolved yet. mapping(bytes32 => uint256) public payoutDenominator; constructor() ERC1155("") {} /// @notice Register a new condition. Anyone may call this; the oracle is /// pinned by being hashed into `conditionId`. /// @param oracle Address that will be allowed to report payouts. /// @param questionId Opaque identifier (interpretation is oracle-specific). /// @param outcomeSlotCount Number of mutually-exclusive outcomes (2..255). /// @dev The upper bound is 255, not 256, because the split/merge/redeem /// paths compute `(1 << outcomeSlotCount) - 1` to derive the full /// index set, and Solidity 0.8 reverts on `1 << 256`. /// @dev Intentionally permissionless: the oracle address is hashed into conditionId, /// so only that oracle can ever report payouts for this condition. function prepareCondition(address oracle, bytes32 questionId, uint256 outcomeSlotCount) external { if (outcomeSlotCount <= 1 || outcomeSlotCount > 255) revert InvalidOutcomeSlotCount(); bytes32 conditionId = CTHelpers.getConditionId(oracle, questionId, outcomeSlotCount); if (payoutNumerators[conditionId].length != 0) revert ConditionAlreadyPrepared(); payoutNumerators[conditionId] = new uint256[](outcomeSlotCount); emit ConditionPreparation(conditionId, oracle, questionId, outcomeSlotCount); } /// @notice Report the final payout vector for a condition. Callable /// exactly once, only by the oracle pinned in `conditionId` /// (via `msg.sender` matching the hash inputs from preparation). /// @param questionId The same `questionId` used at preparation. /// @param payouts Per-slot numerators. At least one must be non-zero. function reportPayouts(bytes32 questionId, uint256[] calldata payouts) external { uint256 outcomeSlotCount = payouts.length; if (outcomeSlotCount <= 1) revert InvalidOutcomeSlotCount(); bytes32 conditionId = CTHelpers.getConditionId(msg.sender, questionId, outcomeSlotCount); uint256[] storage stored = payoutNumerators[conditionId]; if (stored.length != outcomeSlotCount) revert ConditionNotPrepared(); if (payoutDenominator[conditionId] != 0) revert PayoutsAlreadyReported(); uint256 den; for (uint256 i = 0; i < outcomeSlotCount; i++) { uint256 num = payouts[i]; den += num; stored[i] = num; } if (den == 0) revert PayoutIsAllZeroes(); payoutDenominator[conditionId] = den; emit ConditionResolution(conditionId, msg.sender, questionId, outcomeSlotCount, payouts); } /// @notice Split a parent position (collateral if `parentCollectionId == 0`, /// else the parent outcome token) into per-index-set outcome tokens. /// For a full partition covering every outcome slot, this is the /// "mint complete set" primitive. /// @param collateralToken ERC-20 used as the root of this token tree. /// @param parentCollectionId `bytes32(0)` to split from collateral; otherwise the /// parent collection (the position being subdivided). /// @param conditionId The condition whose outcomes are being split. /// @param partition Disjoint, non-zero index sets whose union must lie /// within the condition's full index set. If their /// union equals the full set, the caller pays collateral /// (or burns the parent position); otherwise the caller /// burns the complement-set position. /// @param amount Quantity of each new outcome token to mint. function splitPosition( IERC20 collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] calldata partition, uint256 amount ) external nonReentrant { if (partition.length <= 1) revert InvalidPartition(); uint256 outcomeSlotCount = payoutNumerators[conditionId].length; if (outcomeSlotCount == 0) revert ConditionNotPrepared(); uint256 fullIndexSet = (uint256(1) << outcomeSlotCount) - 1; uint256 freeIndexSet = fullIndexSet; uint256[] memory positionIds = new uint256[](partition.length); uint256[] memory amounts = new uint256[](partition.length); for (uint256 i = 0; i < partition.length; i++) { uint256 indexSet = partition[i]; if (indexSet == 0 || indexSet > fullIndexSet) revert InvalidIndexSet(); if ((indexSet & freeIndexSet) != indexSet) revert InvalidPartition(); freeIndexSet ^= indexSet; positionIds[i] = CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(parentCollectionId, conditionId, indexSet)); amounts[i] = amount; } if (freeIndexSet == 0) { if (parentCollectionId == bytes32(0)) { collateralToken.safeTransferFrom(msg.sender, address(this), amount); } else { _burn(msg.sender, CTHelpers.getPositionId(collateralToken, parentCollectionId), amount); } } else { _burn( msg.sender, CTHelpers.getPositionId( collateralToken, CTHelpers.getCollectionId(parentCollectionId, conditionId, fullIndexSet ^ freeIndexSet) ), amount ); } _mintBatch(msg.sender, positionIds, amounts, ""); emit PositionSplit(msg.sender, collateralToken, parentCollectionId, conditionId, partition, amount); } /// @notice Inverse of `splitPosition`. Burn per-index-set outcome tokens and /// return collateral (or mint the parent / complement position). /// For a full partition this is the "merge complete set" primitive. /// @param collateralToken ERC-20 used as the root of this token tree. /// @param parentCollectionId `bytes32(0)` to recover collateral; otherwise mint /// the parent position. /// @param conditionId The condition whose outcomes are being merged. /// @param partition Disjoint, non-zero index sets (same constraints as `splitPosition`). /// @param amount Quantity of each outcome token to burn. function mergePositions( IERC20 collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] calldata partition, uint256 amount ) external nonReentrant { if (partition.length <= 1) revert InvalidPartition(); uint256 outcomeSlotCount = payoutNumerators[conditionId].length; if (outcomeSlotCount == 0) revert ConditionNotPrepared(); uint256 fullIndexSet = (uint256(1) << outcomeSlotCount) - 1; uint256 freeIndexSet = fullIndexSet; uint256[] memory positionIds = new uint256[](partition.length); uint256[] memory amounts = new uint256[](partition.length); for (uint256 i = 0; i < partition.length; i++) { uint256 indexSet = partition[i]; if (indexSet == 0 || indexSet > fullIndexSet) revert InvalidIndexSet(); if ((indexSet & freeIndexSet) != indexSet) revert InvalidPartition(); freeIndexSet ^= indexSet; positionIds[i] = CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(parentCollectionId, conditionId, indexSet)); amounts[i] = amount; } _burnBatch(msg.sender, positionIds, amounts); if (freeIndexSet == 0) { if (parentCollectionId == bytes32(0)) { collateralToken.safeTransfer(msg.sender, amount); } else { _mint(msg.sender, CTHelpers.getPositionId(collateralToken, parentCollectionId), amount, ""); } } else { _mint( msg.sender, CTHelpers.getPositionId( collateralToken, CTHelpers.getCollectionId(parentCollectionId, conditionId, fullIndexSet ^ freeIndexSet) ), amount, "" ); } emit PositionsMerge(msg.sender, collateralToken, parentCollectionId, conditionId, partition, amount); } /// @notice Redeem the caller's outcome tokens for the listed index sets against /// a resolved condition. Burns the entire balance held for each /// redeemed position and pays out collateral (or mints the parent /// position when `parentCollectionId != 0`). /// @dev Payouts are computed per index set as `(stake * numerator) / denominator` /// with **integer division** (floor). For the typical resolution /// (single winner, denominator = 1) there is no rounding at all. /// For partial payouts the loss is bounded by `(denominator - 1)` /// token-wei per index set — effectively zero on 18-decimal /// collateral, sub-cent on USDC. Dust accumulates in this contract /// and is not swept anywhere. /// @param collateralToken ERC-20 used as the root of this token tree. /// @param parentCollectionId `bytes32(0)` to redeem for collateral, else mint the parent. /// @param conditionId The (resolved) condition. /// @param indexSets Index sets identifying the caller's outcome tokens to redeem. function redeemPositions( IERC20 collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] calldata indexSets ) external nonReentrant { uint256 den = payoutDenominator[conditionId]; if (den == 0) revert ResultNotReceived(); uint256 outcomeSlotCount = payoutNumerators[conditionId].length; if (outcomeSlotCount == 0) revert ConditionNotPrepared(); uint256 totalPayout; uint256 fullIndexSet = (uint256(1) << outcomeSlotCount) - 1; uint256 seenSets; for (uint256 i = 0; i < indexSets.length; i++) { uint256 indexSet = indexSets[i]; if (indexSet == 0 || indexSet > fullIndexSet) revert InvalidIndexSet(); if (seenSets & indexSet != 0) revert InvalidIndexSet(); seenSets |= indexSet; uint256 positionId = CTHelpers.getPositionId( collateralToken, CTHelpers.getCollectionId(parentCollectionId, conditionId, indexSet) ); uint256 payoutNumerator = _sumPayoutNumerators(conditionId, indexSet, outcomeSlotCount); uint256 stake = balanceOf(msg.sender, positionId); if (stake > 0) { totalPayout += (stake * payoutNumerator) / den; _burn(msg.sender, positionId, stake); } } if (totalPayout > 0) { if (parentCollectionId == bytes32(0)) { collateralToken.safeTransfer(msg.sender, totalPayout); } else { _mint(msg.sender, CTHelpers.getPositionId(collateralToken, parentCollectionId), totalPayout, ""); } } emit PayoutRedemption(msg.sender, collateralToken, parentCollectionId, conditionId, indexSets, totalPayout); } /// @dev Sum the per-outcome payout numerators selected by `indexSet`. /// Extracted from `redeemPositions` so the inner loop's `j` counter /// lives in a separate stack frame — coverage instrumentation pushes /// the combined frame over the Yul 16-slot limit otherwise. function _sumPayoutNumerators(bytes32 conditionId, uint256 indexSet, uint256 outcomeSlotCount) internal view returns (uint256 sum) { for (uint256 j = 0; j < outcomeSlotCount; j++) { if ((indexSet & (uint256(1) << j)) != 0) { sum += payoutNumerators[conditionId][j]; } } } /// @notice Returns `outcomeSlotCount` for a prepared condition, or `0` if /// the condition has not been prepared. function getOutcomeSlotCount(bytes32 conditionId) external view returns (uint256) { return payoutNumerators[conditionId].length; } // ---- ID derivation helpers ------------------------------------------ // // Pure passthroughs to the CTHelpers library. Exposed so frontend / // indexer / external integrations can read IDs via staticcall instead // of duplicating the keccak chain offchain. /// @notice Derive a condition id from its (oracle, questionId, slot count) tuple. function getConditionId(address oracle, bytes32 questionId, uint256 outcomeSlotCount) external pure returns (bytes32) { return CTHelpers.getConditionId(oracle, questionId, outcomeSlotCount); } /// @notice Derive a collection id from a parent collection, condition, and index set. function getCollectionId(bytes32 parentCollectionId, bytes32 conditionId, uint256 indexSet) external pure returns (bytes32) { return CTHelpers.getCollectionId(parentCollectionId, conditionId, indexSet); } /// @notice Derive a position id (the ERC-1155 token id) from a collateral and collection. function getPositionId(IERC20 collateralToken, bytes32 collectionId) external pure returns (uint256) { return CTHelpers.getPositionId(collateralToken, collectionId); } }lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol) pragma solidity ^0.8.20; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at, * consider using {ReentrancyGuardTransient} instead. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = 2; uint256 private _status; /** * @dev Unauthorized reentrant call. */ error ReentrancyGuardReentrantCall(); constructor() { _status = NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { _nonReentrantBefore(); _; _nonReentrantAfter(); } function _nonReentrantBefore() private { // On the first call to nonReentrant, _status will be NOT_ENTERED if (_status == ENTERED) { revert ReentrancyGuardReentrantCall(); } // Any calls to nonReentrant after this point will fail _status = ENTERED; } function _nonReentrantAfter() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = NOT_ENTERED; } /** * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a * `nonReentrant` function in the call stack. */ function _reentrancyGuardEntered() internal view returns (bool) { return _status == ENTERED; } }lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.20; /** * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeCast { /** * @dev Value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value); /** * @dev An int value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedIntToUint(int256 value); /** * @dev Value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedIntDowncast(uint8 bits, int256 value); /** * @dev An uint value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedUintToInt(uint256 value); /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits */ function toUint248(uint256 value) internal pure returns (uint248) { if (value > type(uint248).max) { revert SafeCastOverflowedUintDowncast(248, value); } return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits */ function toUint240(uint256 value) internal pure returns (uint240) { if (value > type(uint240).max) { revert SafeCastOverflowedUintDowncast(240, value); } return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits */ function toUint232(uint256 value) internal pure returns (uint232) { if (value > type(uint232).max) { revert SafeCastOverflowedUintDowncast(232, value); } return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { if (value > type(uint224).max) { revert SafeCastOverflowedUintDowncast(224, value); } return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits */ function toUint216(uint256 value) internal pure returns (uint216) { if (value > type(uint216).max) { revert SafeCastOverflowedUintDowncast(216, value); } return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits */ function toUint208(uint256 value) internal pure returns (uint208) { if (value > type(uint208).max) { revert SafeCastOverflowedUintDowncast(208, value); } return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits */ function toUint200(uint256 value) internal pure returns (uint200) { if (value > type(uint200).max) { revert SafeCastOverflowedUintDowncast(200, value); } return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { if (value > type(uint192).max) { revert SafeCastOverflowedUintDowncast(192, value); } return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits */ function toUint184(uint256 value) internal pure returns (uint184) { if (value > type(uint184).max) { revert SafeCastOverflowedUintDowncast(184, value); } return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits */ function toUint176(uint256 value) internal pure returns (uint176) { if (value > type(uint176).max) { revert SafeCastOverflowedUintDowncast(176, value); } return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits */ function toUint168(uint256 value) internal pure returns (uint168) { if (value > type(uint168).max) { revert SafeCastOverflowedUintDowncast(168, value); } return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits */ function toUint160(uint256 value) internal pure returns (uint160) { if (value > type(uint160).max) { revert SafeCastOverflowedUintDowncast(160, value); } return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits */ function toUint152(uint256 value) internal pure returns (uint152) { if (value > type(uint152).max) { revert SafeCastOverflowedUintDowncast(152, value); } return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits */ function toUint144(uint256 value) internal pure returns (uint144) { if (value > type(uint144).max) { revert SafeCastOverflowedUintDowncast(144, value); } return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits */ function toUint136(uint256 value) internal pure returns (uint136) { if (value > type(uint136).max) { revert SafeCastOverflowedUintDowncast(136, value); } return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { if (value > type(uint128).max) { revert SafeCastOverflowedUintDowncast(128, value); } return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits */ function toUint120(uint256 value) internal pure returns (uint120) { if (value > type(uint120).max) { revert SafeCastOverflowedUintDowncast(120, value); } return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits */ function toUint112(uint256 value) internal pure returns (uint112) { if (value > type(uint112).max) { revert SafeCastOverflowedUintDowncast(112, value); } return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits */ function toUint104(uint256 value) internal pure returns (uint104) { if (value > type(uint104).max) { revert SafeCastOverflowedUintDowncast(104, value); } return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { if (value > type(uint96).max) { revert SafeCastOverflowedUintDowncast(96, value); } return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits */ function toUint88(uint256 value) internal pure returns (uint88) { if (value > type(uint88).max) { revert SafeCastOverflowedUintDowncast(88, value); } return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits */ function toUint80(uint256 value) internal pure returns (uint80) { if (value > type(uint80).max) { revert SafeCastOverflowedUintDowncast(80, value); } return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits */ function toUint72(uint256 value) internal pure returns (uint72) { if (value > type(uint72).max) { revert SafeCastOverflowedUintDowncast(72, value); } return uint72(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { if (value > type(uint64).max) { revert SafeCastOverflowedUintDowncast(64, value); } return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits */ function toUint56(uint256 value) internal pure returns (uint56) { if (value > type(uint56).max) { revert SafeCastOverflowedUintDowncast(56, value); } return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits */ function toUint48(uint256 value) internal pure returns (uint48) { if (value > type(uint48).max) { revert SafeCastOverflowedUintDowncast(48, value); } return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits */ function toUint40(uint256 value) internal pure returns (uint40) { if (value > type(uint40).max) { revert SafeCastOverflowedUintDowncast(40, value); } return uint40(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { if (value > type(uint32).max) { revert SafeCastOverflowedUintDowncast(32, value); } return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits */ function toUint24(uint256 value) internal pure returns (uint24) { if (value > type(uint24).max) { revert SafeCastOverflowedUintDowncast(24, value); } return uint24(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { if (value > type(uint16).max) { revert SafeCastOverflowedUintDowncast(16, value); } return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits */ function toUint8(uint256 value) internal pure returns (uint8) { if (value > type(uint8).max) { revert SafeCastOverflowedUintDowncast(8, value); } return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { if (value < 0) { revert SafeCastOverflowedIntToUint(value); } return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(248, value); } } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(240, value); } } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(232, value); } } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(224, value); } } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(216, value); } } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(208, value); } } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(200, value); } } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(192, value); } } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(184, value); } } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(176, value); } } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(168, value); } } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(160, value); } } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(152, value); } } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(144, value); } } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(136, value); } } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits */ function toInt128(int256 value) internal pure returns (int128 downcasted) { downcasted = int128(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(128, value); } } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(120, value); } } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(112, value); } } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(104, value); } } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(96, value); } } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(88, value); } } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(80, value); } } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(72, value); } } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits */ function toInt64(int256 value) internal pure returns (int64 downcasted) { downcasted = int64(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(64, value); } } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(56, value); } } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(48, value); } } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(40, value); } } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits */ function toInt32(int256 value) internal pure returns (int32 downcasted) { downcasted = int32(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(32, value); } } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(24, value); } } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits */ function toInt16(int256 value) internal pure returns (int16 downcasted) { downcasted = int16(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(16, value); } } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits */ function toInt8(int256 value) internal pure returns (int8 downcasted) { downcasted = int8(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(8, value); } } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive if (value > uint256(type(int256).max)) { revert SafeCastOverflowedUintToInt(value); } return int256(value); } /** * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump. */ function toUint(bool b) internal pure returns (uint256 u) { assembly ("memory-safe") { u := iszero(iszero(b)) } } }lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol) pragma solidity ^0.8.20; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` */ abstract contract ERC165Upgradeable is Initializable, IERC165 { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == type(IERC165).interfaceId; } }lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol) pragma solidity ^0.8.20; /** * @dev Collection of common custom errors used in multiple contracts * * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library. * It is recommended to avoid relying on the error API for critical functionality. * * _Available since v5.1._ */ library Errors { /** * @dev The ETH balance of the account is not enough to perform the operation. */ error InsufficientBalance(uint256 balance, uint256 needed); /** * @dev A call to an address target failed. The target may have reverted. */ error FailedCall(); /** * @dev The deployment failed. */ error FailedDeployment(); /** * @dev A necessary precompile is missing. */ error MissingPrecompile(address); }lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.20; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {UpgradeableBeacon} will check that this address is a contract. */ function implementation() external view returns (address); }lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1271.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC-1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); }lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/SignatureChecker.sol) pragma solidity ^0.8.20; import {ECDSA} from "./ECDSA.sol"; import {IERC1271} from "../../interfaces/IERC1271.sol"; /** * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA * signatures from externally owned accounts (EOAs) as well as ERC-1271 signatures from smart contract wallets like * Argent and Safe Wallet (previously Gnosis Safe). */ library SignatureChecker { /** * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the * signature is validated against that smart contract using ERC-1271, otherwise it's validated using `ECDSA.recover`. * * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus * change through time. It could return true at block N and false at block N+1 (or the opposite). */ function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) { if (signer.code.length == 0) { (address recovered, ECDSA.RecoverError err, ) = ECDSA.tryRecover(hash, signature); return err == ECDSA.RecoverError.NoError && recovered == signer; } else { return isValidERC1271SignatureNow(signer, hash, signature); } } /** * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated * against the signer smart contract using ERC-1271. * * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus * change through time. It could return true at block N and false at block N+1 (or the opposite). */ function isValidERC1271SignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (bool success, bytes memory result) = signer.staticcall( abi.encodeCall(IERC1271.isValidSignature, (hash, signature)) ); return (success && result.length >= 32 && abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector)); } }lib/openzeppelin-contracts-upgradeable/contracts/token/ERC1155/utils/ERC1155HolderUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/utils/ERC1155Holder.sol) pragma solidity ^0.8.20; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {ERC165Upgradeable} from "../../../utils/introspection/ERC165Upgradeable.sol"; import {IERC1155Receiver} from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import {Initializable} from "../../../proxy/utils/Initializable.sol"; /** * @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC-1155 tokens. * * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be * stuck. */ abstract contract ERC1155HolderUpgradeable is Initializable, ERC165Upgradeable, IERC1155Receiver { function __ERC1155Holder_init() internal onlyInitializing { } function __ERC1155Holder_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); } function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } }lib/openzeppelin-contracts/contracts/utils/Comparators.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol) pragma solidity ^0.8.20; /** * @dev Provides a set of functions to compare values. * * _Available since v5.1._ */ library Comparators { function lt(uint256 a, uint256 b) internal pure returns (bool) { return a < b; } function gt(uint256 a, uint256 b) internal pure returns (bool) { return a > b; } }lib/openzeppelin-contracts/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.20; import {IERC1155} from "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[ERC]. */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); }lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol) // This file was procedurally generated from scripts/generate/templates/StorageSlot.js. pragma solidity ^0.8.20; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC-1967 implementation slot: * ```solidity * contract ERC1967 { * // Define the slot. Alternatively, use the SlotDerivation library to derive the slot. * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(newImplementation.code.length > 0); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * TIP: Consider using this library along with {SlotDerivation}. */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } struct Int256Slot { int256 value; } struct StringSlot { string value; } struct BytesSlot { bytes value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `Int256Slot` with member `value` located at `slot`. */ function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns a `StringSlot` with member `value` located at `slot`. */ function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns an `StringSlot` representation of the string storage pointer `store`. */ function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { assembly ("memory-safe") { r.slot := store.slot } } /** * @dev Returns a `BytesSlot` with member `value` located at `slot`. */ function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { assembly ("memory-safe") { r.slot := slot } } /** * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. */ function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { assembly ("memory-safe") { r.slot := store.slot } } }lib/openzeppelin-contracts/contracts/utils/SlotDerivation.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/SlotDerivation.sol) // This file was procedurally generated from scripts/generate/templates/SlotDerivation.js. pragma solidity ^0.8.20; /** * @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots * corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by * the solidity language / compiler. * * See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.]. * * Example usage: * ```solidity * contract Example { * // Add the library methods * using StorageSlot for bytes32; * using SlotDerivation for bytes32; * * // Declare a namespace * string private constant _NAMESPACE = "<namespace>" // eg. OpenZeppelin.Slot * * function setValueInNamespace(uint256 key, address newValue) internal { * _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue; * } * * function getValueInNamespace(uint256 key) internal view returns (address) { * return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value; * } * } * ``` * * TIP: Consider using this library along with {StorageSlot}. * * NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking * upgrade safety will ignore the slots accessed through this library. * * _Available since v5.1._ */ library SlotDerivation { /** * @dev Derive an ERC-7201 slot from a string (namespace). */ function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) { assembly ("memory-safe") { mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1)) slot := and(keccak256(0x00, 0x20), not(0xff)) } } /** * @dev Add an offset to a slot to get the n-th element of a structure or an array. */ function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) { unchecked { return bytes32(uint256(slot) + pos); } } /** * @dev Derive the location of the first element in an array from the slot where the length is stored. */ function deriveArray(bytes32 slot) internal pure returns (bytes32 result) { assembly ("memory-safe") { mstore(0x00, slot) result := keccak256(0x00, 0x20) } } /** * @dev Derive the location of a mapping element from the key. */ function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) { assembly ("memory-safe") { mstore(0x00, and(key, shr(96, not(0)))) mstore(0x20, slot) result := keccak256(0x00, 0x40) } } /** * @dev Derive the location of a mapping element from the key. */ function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) { assembly ("memory-safe") { mstore(0x00, iszero(iszero(key))) mstore(0x20, slot) result := keccak256(0x00, 0x40) } } /** * @dev Derive the location of a mapping element from the key. */ function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) { assembly ("memory-safe") { mstore(0x00, key) mstore(0x20, slot) result := keccak256(0x00, 0x40) } } /** * @dev Derive the location of a mapping element from the key. */ function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) { assembly ("memory-safe") { mstore(0x00, key) mstore(0x20, slot) result := keccak256(0x00, 0x40) } } /** * @dev Derive the location of a mapping element from the key. */ function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) { assembly ("memory-safe") { mstore(0x00, key) mstore(0x20, slot) result := keccak256(0x00, 0x40) } } /** * @dev Derive the location of a mapping element from the key. */ function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) { assembly ("memory-safe") { let length := mload(key) let begin := add(key, 0x20) let end := add(begin, length) let cache := mload(end) mstore(end, slot) result := keccak256(begin, add(length, 0x20)) mstore(end, cache) } } /** * @dev Derive the location of a mapping element from the key. */ function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) { assembly ("memory-safe") { let length := mload(key) let begin := add(key, 0x20) let end := add(begin, length) let cache := mload(end) mstore(end, slot) result := keccak256(begin, add(length, 0x20)) mstore(end, cache) } } }lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol) pragma solidity ^0.8.20; import {IERC165} from "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == type(IERC165).interfaceId; } }lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol) pragma solidity ^0.8.20; /** * @dev Standard ERC-20 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens. */ interface IERC20Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC20InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC20InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers. * @param spender Address that may be allowed to operate on tokens without being their owner. * @param allowance Amount of tokens a `spender` is allowed to operate with. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC20InvalidApprover(address approver); /** * @dev Indicates a failure with the `spender` to be approved. Used in approvals. * @param spender Address that may be allowed to operate on tokens without being their owner. */ error ERC20InvalidSpender(address spender); } /** * @dev Standard ERC-721 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens. */ interface IERC721Errors { /** * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20. * Used in balance queries. * @param owner Address of the current owner of a token. */ error ERC721InvalidOwner(address owner); /** * @dev Indicates a `tokenId` whose `owner` is the zero address. * @param tokenId Identifier number of a token. */ error ERC721NonexistentToken(uint256 tokenId); /** * @dev Indicates an error related to the ownership over a particular token. Used in transfers. * @param sender Address whose tokens are being transferred. * @param tokenId Identifier number of a token. * @param owner Address of the current owner of a token. */ error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC721InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC721InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param tokenId Identifier number of a token. */ error ERC721InsufficientApproval(address operator, uint256 tokenId); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC721InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC721InvalidOperator(address operator); } /** * @dev Standard ERC-1155 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens. */ interface IERC1155Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. * @param tokenId Identifier number of a token. */ error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC1155InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC1155InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param owner Address of the current owner of a token. */ error ERC1155MissingApprovalForAll(address operator, address owner); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC1155InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC1155InvalidOperator(address operator); /** * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation. * Used in batch transfers. * @param idsLength Length of the array of token identifiers * @param valuesLength Length of the array of token amounts */ error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength); }lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.20; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ```solidity * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Storage of the initializable contract. * * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions * when using with upgradeable contracts. * * @custom:storage-location erc7201:openzeppelin.storage.Initializable */ struct InitializableStorage { /** * @dev Indicates that the contract has been initialized. */ uint64 _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool _initializing; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00; /** * @dev The contract is already initialized. */ error InvalidInitialization(); /** * @dev The contract is not initializing. */ error NotInitializing(); /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint64 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in * production. * * Emits an {Initialized} event. */ modifier initializer() { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); // Cache values to avoid duplicated sloads bool isTopLevelCall = !$._initializing; uint64 initialized = $._initialized; // Allowed calls: // - initialSetup: the contract is not in the initializing state and no previous version was // initialized // - construction: the contract is initialized at version 1 (no reininitialization) and the // current contract is just being deployed bool initialSetup = initialized == 0 && isTopLevelCall; bool construction = initialized == 1 && address(this).code.length == 0; if (!initialSetup && !construction) { revert InvalidInitialization(); } $._initialized = 1; if (isTopLevelCall) { $._initializing = true; } _; if (isTopLevelCall) { $._initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint64 version) { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); if ($._initializing || $._initialized >= version) { revert InvalidInitialization(); } $._initialized = version; $._initializing = true; _; $._initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { _checkInitializing(); _; } /** * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}. */ function _checkInitializing() internal view virtual { if (!_isInitializing()) { revert NotInitializing(); } } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); if ($._initializing) { revert InvalidInitialization(); } if ($._initialized != type(uint64).max) { $._initialized = type(uint64).max; emit Initialized(type(uint64).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint64) { return _getInitializableStorage()._initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _getInitializableStorage()._initializing; } /** * @dev Returns a pointer to the storage namespace. */ // solhint-disable-next-line var-name-mixedcase function _getInitializableStorage() private pure returns (InitializableStorage storage $) { assembly { $.slot := INITIALIZABLE_STORAGE } } }src/interfaces/IWETH9.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH9 is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; }lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol) pragma solidity ^0.8.20; import {Errors} from "./Errors.sol"; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev There's no code at `target` (it is not a contract). */ error AddressEmptyCode(address target); /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { if (address(this).balance < amount) { revert Errors.InsufficientBalance(address(this).balance, amount); } (bool success, ) = recipient.call{value: amount}(""); if (!success) { revert Errors.FailedCall(); } } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason or custom error, it is bubbled * up by this function (like regular Solidity function calls). However, if * the call reverted with no returned reason, this function reverts with a * {Errors.FailedCall} error. * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { if (address(this).balance < value) { revert Errors.InsufficientBalance(address(this).balance, value); } (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case * of an unsuccessful call. */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata ) internal view returns (bytes memory) { if (!success) { _revert(returndata); } else { // only check if target is a contract if the call was successful and the return data is empty // otherwise we already know that it was a contract if (returndata.length == 0 && target.code.length == 0) { revert AddressEmptyCode(target); } return returndata; } } /** * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the * revert reason or with a default {Errors.FailedCall} error. */ function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) { if (!success) { _revert(returndata); } else { return returndata; } } /** * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}. */ function _revert(bytes memory returndata) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly ("memory-safe") { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert Errors.FailedCall(); } } }lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MessageHashUtils.sol) pragma solidity ^0.8.20; import {Strings} from "../Strings.sol"; /** * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing. * * The library provides methods for generating a hash of a message that conforms to the * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712] * specifications. */ library MessageHashUtils { /** * @dev Returns the keccak256 digest of an ERC-191 signed data with version * `0x45` (`personal_sign` messages). * * The digest is calculated by prefixing a bytes32 `messageHash` with * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method. * * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with * keccak256, although any bytes32 value can be safely used because the final digest will * be re-hashed. * * See {ECDSA-recover}. */ function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) { assembly ("memory-safe") { mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20) } } /** * @dev Returns the keccak256 digest of an ERC-191 signed data with version * `0x45` (`personal_sign` messages). * * The digest is calculated by prefixing an arbitrary `message` with * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method. * * See {ECDSA-recover}. */ function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) { return keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message)); } /** * @dev Returns the keccak256 digest of an ERC-191 signed data with version * `0x00` (data with intended validator). * * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended * `validator` address. Then hashing the result. * * See {ECDSA-recover}. */ function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) { return keccak256(abi.encodePacked(hex"19_00", validator, data)); } /** * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`). * * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with * `\x19\x01` and hashing the result. It corresponds to the hash signed by the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712. * * See {ECDSA-recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) { assembly ("memory-safe") { let ptr := mload(0x40) mstore(ptr, hex"19_01") mstore(add(ptr, 0x02), domainSeparator) mstore(add(ptr, 0x22), structHash) digest := keccak256(ptr, 0x42) } } }src/interfaces/IVenuePolicy.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// @title IVenuePolicy /// @notice Pluggable access-control hook a venue can attach to its `Venue` /// record in the registry. The router consults a venue's policy at /// three decision points; each method returns `false` to deny. /// /// A venue's policy contract serves all three callbacks. Implementations /// pick which dimensions they actually gate; the others can return `true` /// unconditionally. Setting the policy address to `address(0)` on a /// venue disables all three checks for that venue (the protocol default). /// /// Implements ERC-165. The registry validates `supportsInterface` before /// accepting a policy address, so passing a non-conforming address reverts. interface IVenuePolicy is IERC165 { /// @notice Called when `user` attempts to create a market through this /// venue (i.e. tagging the create-market call with this venue's id). /// Use this for KYC / allowlist gates on market creators. function canCreateMarket(address user) external view returns (bool); /// @notice Called when `user` attempts to buy/sell through this venue. /// `conditionId` lets the policy gate on a per-market basis (e.g. /// "this venue only allows verified accounts to trade on real-money /// markets; demo markets are open"). function canTrade(address user, bytes32 conditionId) external view returns (bool); /// @notice Called when a *different* venue (`routingVenueId`) attempts to /// route a trade against a market that *this* venue originated. /// Lets a market-creating venue gate which counterparties may /// facilitate trades on its markets. Returning `false` blocks the /// trade. /// /// Skipped entirely when the routing venue and the origin venue /// are the same (a venue never gates itself). Skipped when the /// origin venue is 0 (the market was created without a venue — /// there is no origin policy to consult). /// /// A `routingVenueId` of 0 represents a venueless ("direct") trade /// path; an origin venue can still refuse it by returning `false`, /// which is the lever for "all trades on my markets must go through /// an approved routing venue". function canRoute(uint32 routingVenueId, bytes32 conditionId) external view returns (bool); }lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.20; import {IERC165} from "../../utils/introspection/IERC165.sol"; /** * @dev Interface that must be implemented by smart contracts in order to receive * ERC-1155 token transfers. */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC-1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC-1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); }
ABI · 131 entries
json
[
{
"type": "constructor",
"inputs": [],
"stateMutability": "nonpayable"
},
{
"name": "AdapterNotApproved",
"type": "error",
"inputs": []
},
{
"name": "AddressEmptyCode",
"type": "error",
"inputs": [
{
"name": "target",
"type": "address",
"internalType": "address"
}
]
},
{
"name": "ClaimFeesAuthExpired",
"type": "error",
"inputs": []
},
{
"name": "ClaimFeesNonceUsed",
"type": "error",
"inputs": []
},
{
"name": "ClaimFeesSignatureInvalid",
"type": "error",
"inputs": []
},
{
"name": "ERC1967InvalidImplementation",
"type": "error",
"inputs": [
{
"name": "implementation",
"type": "address",
"internalType": "address"
}
]
},
{
"name": "ERC1967NonPayable",
"type": "error",
"inputs": []
},
{
"name": "EthRefundFailed",
"type": "error",
"inputs": []
},
{
"name": "FailedCall",
"type": "error",
"inputs": []
},
{
"name": "FeeExceedsMax",
"type": "error",
"inputs": []
},
{
"name": "InvalidAdapter",
"type": "error",
"inputs": []
},
{
"name": "InvalidFee",
"type": "error",
"inputs": []
},
{
"name": "InvalidInitialization",
"type": "error",
"inputs": []
},
{
"name": "InvalidOutcomeIndex",
"type": "error",
"inputs": []
},
{
"name": "InvalidPermitToken",
"type": "error",
"inputs": []
},
{
"name": "InvalidTradingWindow",
"type": "error",
"inputs": []
},
{
"name": "InvalidVenueSignature",
"type": "error",
"inputs": []
},
{
"name": "LiquidityFrozen",
"type": "error",
"inputs": []
},
{
"name": "MaxAmountExceeded",
"type": "error",
"inputs": []
},
{
"name": "NativeAmountMismatch",
"type": "error",
"inputs": []
},
{
"name": "NativeNotSupported",
"type": "error",
"inputs": []
},
{
"name": "NativeTransferFailed",
"type": "error",
"inputs": []
},
{
"name": "NotAuthorizedAdapter",
"type": "error",
"inputs": []
},
{
"name": "NotInitializing",
"type": "error",
"inputs": []
},
{
"name": "OracleNotAnswered",
"type": "error",
"inputs": []
},
{
"name": "OutcomeCountMismatch",
"type": "error",
"inputs": []
},
{
"name": "OwnableInvalidOwner",
"type": "error",
"inputs": [
{
"name": "owner",
"type": "address",
"internalType": "address"
}
]
},
{
"name": "OwnableUnauthorizedAccount",
"type": "error",
"inputs": [
{
"name": "account",
"type": "address",
"internalType": "address"
}
]
},
{
"name": "Permit2NotConfigured",
"type": "error",
"inputs": []
},
{
"name": "RedeemAuthExpired",
"type": "error",
"inputs": []
},
{
"name": "RedeemNonceUsed",
"type": "error",
"inputs": []
},
{
"name": "RedeemSignatureInvalid",
"type": "error",
"inputs": []
},
{
"name": "ReentrancyGuardReentrantCall",
"type": "error",
"inputs": []
},
{
"name": "SafeERC20FailedOperation",
"type": "error",
"inputs": [
{
"name": "token",
"type": "address",
"internalType": "address"
}
]
},
{
"name": "TooManyMarketsForQuestion",
"type": "error",
"inputs": []
},
{
"name": "UUPSUnauthorizedCallContext",
"type": "error",
"inputs": []
},
{
"name": "UUPSUnsupportedProxiableUUID",
"type": "error",
"inputs": [
{
"name": "slot",
"type": "bytes32",
"internalType": "bytes32"
}
]
},
{
"name": "UnderpaidScheduleFee",
"type": "error",
"inputs": []
},
{
"name": "UnknownMarket",
"type": "error",
"inputs": []
},
{
"name": "UnknownOracleQuestion",
"type": "error",
"inputs": []
},
{
"name": "VenueAuthExpired",
"type": "error",
"inputs": []
},
{
"name": "VenueNonceUsed",
"type": "error",
"inputs": []
},
{
"name": "VenuePolicyDenied",
"type": "error",
"inputs": []
},
{
"name": "VenueSignerUnset",
"type": "error",
"inputs": []
},
{
"name": "WithdrawFailed",
"type": "error",
"inputs": []
},
{
"name": "ZeroAddress",
"type": "error",
"inputs": []
},
{
"name": "ZeroLiquidity",
"type": "error",
"inputs": []
},
{
"name": "AdapterApproved",
"type": "event",
"inputs": [
{
"name": "adapter",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "approved",
"type": "bool",
"indexed": false,
"internalType": "bool"
}
],
"anonymous": false
},
{
"name": "Deposited",
"type": "event",
"inputs": [
{
"name": "from",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "amount",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
}
],
"anonymous": false
},
{
"name": "EIP712DomainChanged",
"type": "event",
"inputs": [],
"anonymous": false
},
{
"name": "Initialized",
"type": "event",
"inputs": [
{
"name": "version",
"type": "uint64",
"indexed": false,
"internalType": "uint64"
}
],
"anonymous": false
},
{
"name": "MarketCreated",
"type": "event",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"indexed": true,
"internalType": "bytes32"
},
{
"name": "market",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "oracleQuestionId",
"type": "uint256",
"indexed": true,
"internalType": "uint256"
},
{
"name": "venueId",
"type": "uint32",
"indexed": false,
"internalType": "uint32"
},
{
"name": "creator",
"type": "address",
"indexed": false,
"internalType": "address"
},
{
"name": "collateralToken",
"type": "address",
"indexed": false,
"internalType": "address"
},
{
"name": "fee",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "outcomeSlotCount",
"type": "uint8",
"indexed": false,
"internalType": "uint8"
},
{
"name": "tradingStart",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "tradingClose",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "voidPolicy",
"type": "uint8",
"indexed": false,
"internalType": "enum PredictionMarketCore.VoidPolicy"
},
{
"name": "marketIndex",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "creatorFeeBps",
"type": "uint16",
"indexed": false,
"internalType": "uint16"
}
],
"anonymous": false
},
{
"name": "MarketCreated",
"type": "event",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"indexed": true,
"internalType": "bytes32"
},
{
"name": "market",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "oracleQuestionId",
"type": "uint256",
"indexed": true,
"internalType": "uint256"
},
{
"name": "venueId",
"type": "uint32",
"indexed": false,
"internalType": "uint32"
},
{
"name": "creator",
"type": "address",
"indexed": false,
"internalType": "address"
},
{
"name": "collateralToken",
"type": "address",
"indexed": false,
"internalType": "address"
},
{
"name": "fee",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "outcomeSlotCount",
"type": "uint8",
"indexed": false,
"internalType": "uint8"
},
{
"name": "tradingStart",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "tradingClose",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "voidPolicy",
"type": "uint8",
"indexed": false,
"internalType": "enum PredictionMarketCore.VoidPolicy"
},
{
"name": "marketIndex",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "creatorFeeBps",
"type": "uint16",
"indexed": false,
"internalType": "uint16"
},
{
"name": "metadata",
"type": "bytes",
"indexed": false,
"internalType": "bytes"
}
],
"anonymous": false
},
{
"name": "MarketResolutionSkipped",
"type": "event",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"indexed": true,
"internalType": "bytes32"
},
{
"name": "outcomeIdx",
"type": "uint8",
"indexed": false,
"internalType": "uint8"
},
{
"name": "slots",
"type": "uint8",
"indexed": false,
"internalType": "uint8"
}
],
"anonymous": false
},
{
"name": "MarketResolved",
"type": "event",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"indexed": true,
"internalType": "bytes32"
},
{
"name": "oracleQuestionId",
"type": "uint256",
"indexed": true,
"internalType": "uint256"
},
{
"name": "outcomeIdx",
"type": "uint8",
"indexed": false,
"internalType": "uint8"
},
{
"name": "voided",
"type": "bool",
"indexed": false,
"internalType": "bool"
},
{
"name": "payouts",
"type": "uint256[]",
"indexed": false,
"internalType": "uint256[]"
}
],
"anonymous": false
},
{
"name": "OwnershipTransferStarted",
"type": "event",
"inputs": [
{
"name": "previousOwner",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "newOwner",
"type": "address",
"indexed": true,
"internalType": "address"
}
],
"anonymous": false
},
{
"name": "OwnershipTransferred",
"type": "event",
"inputs": [
{
"name": "previousOwner",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "newOwner",
"type": "address",
"indexed": true,
"internalType": "address"
}
],
"anonymous": false
},
{
"name": "RouterAddLiquidity",
"type": "event",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"indexed": true,
"internalType": "bytes32"
},
{
"name": "funder",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "venueId",
"type": "uint32",
"indexed": true,
"internalType": "uint32"
},
{
"name": "amount",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "shares",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
}
],
"anonymous": false
},
{
"name": "RouterBuy",
"type": "event",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"indexed": true,
"internalType": "bytes32"
},
{
"name": "trader",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "venueId",
"type": "uint32",
"indexed": true,
"internalType": "uint32"
},
{
"name": "indexSet",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "investmentAmount",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "outcomeTokensBought",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "lpFee",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "venueFee",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "marketVenueFee",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "creatorFee",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
}
],
"anonymous": false
},
{
"name": "RouterMergeCompleteSet",
"type": "event",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"indexed": true,
"internalType": "bytes32"
},
{
"name": "user",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "venueId",
"type": "uint32",
"indexed": true,
"internalType": "uint32"
},
{
"name": "amount",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
}
],
"anonymous": false
},
{
"name": "RouterMintCompleteSet",
"type": "event",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"indexed": true,
"internalType": "bytes32"
},
{
"name": "user",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "venueId",
"type": "uint32",
"indexed": true,
"internalType": "uint32"
},
{
"name": "amount",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
}
],
"anonymous": false
},
{
"name": "RouterRedeem",
"type": "event",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"indexed": true,
"internalType": "bytes32"
},
{
"name": "redeemer",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "venueId",
"type": "uint32",
"indexed": true,
"internalType": "uint32"
}
],
"anonymous": false
},
{
"name": "RouterRemoveLiquidity",
"type": "event",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"indexed": true,
"internalType": "bytes32"
},
{
"name": "funder",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "venueId",
"type": "uint32",
"indexed": true,
"internalType": "uint32"
},
{
"name": "shares",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
}
],
"anonymous": false
},
{
"name": "RouterSell",
"type": "event",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"indexed": true,
"internalType": "bytes32"
},
{
"name": "trader",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "venueId",
"type": "uint32",
"indexed": true,
"internalType": "uint32"
},
{
"name": "outcomeIndex",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "returnAmount",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "amountToTrader",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "outcomeTokensSold",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "lpFee",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "venueFee",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "marketVenueFee",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
},
{
"name": "creatorFee",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
}
],
"anonymous": false
},
{
"name": "RouterWithdrawFees",
"type": "event",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"indexed": true,
"internalType": "bytes32"
},
{
"name": "lp",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "venueId",
"type": "uint32",
"indexed": true,
"internalType": "uint32"
}
],
"anonymous": false
},
{
"name": "Upgraded",
"type": "event",
"inputs": [
{
"name": "implementation",
"type": "address",
"indexed": true,
"internalType": "address"
}
],
"anonymous": false
},
{
"name": "Withdrawn",
"type": "event",
"inputs": [
{
"name": "to",
"type": "address",
"indexed": true,
"internalType": "address"
},
{
"name": "amount",
"type": "uint256",
"indexed": false,
"internalType": "uint256"
}
],
"anonymous": false
},
{
"name": "CLAIM_FEES_AUTH_TYPEHASH",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "",
"type": "bytes32",
"internalType": "bytes32"
}
],
"stateMutability": "view"
},
{
"name": "CONDITIONAL_TOKENS",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "",
"type": "address",
"internalType": "contract ConditionalTokens"
}
],
"stateMutability": "view"
},
{
"name": "MAX_CREATOR_FEE_BPS",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "",
"type": "uint16",
"internalType": "uint16"
}
],
"stateMutability": "view"
},
{
"name": "ORDER_ROUTER",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "",
"type": "address",
"internalType": "contract OrderRouter"
}
],
"stateMutability": "view"
},
{
"name": "PERMIT2",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "",
"type": "address",
"internalType": "address"
}
],
"stateMutability": "view"
},
{
"name": "REDEEM_AUTH_TYPEHASH",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "",
"type": "bytes32",
"internalType": "bytes32"
}
],
"stateMutability": "view"
},
{
"name": "UPGRADE_INTERFACE_VERSION",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "",
"type": "string",
"internalType": "string"
}
],
"stateMutability": "view"
},
{
"name": "VENUE_AUTH_TYPEHASH",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "",
"type": "bytes32",
"internalType": "bytes32"
}
],
"stateMutability": "view"
},
{
"name": "VENUE_REGISTRY",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "",
"type": "address",
"internalType": "contract VenueRegistry"
}
],
"stateMutability": "view"
},
{
"name": "acceptOwnership",
"type": "function",
"inputs": [],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "addLiquidity",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "amount",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "context",
"type": "bytes",
"internalType": "bytes"
}
],
"outputs": [
{
"name": "positionData",
"type": "bytes",
"internalType": "bytes"
}
],
"stateMutability": "payable"
},
{
"name": "addLiquidityWithPermit2",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "amount",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "context",
"type": "bytes",
"internalType": "bytes"
},
{
"name": "permit",
"type": "tuple",
"components": [
{
"name": "permitted",
"type": "tuple",
"components": [
{
"name": "token",
"type": "address",
"internalType": "address"
},
{
"name": "amount",
"type": "uint256",
"internalType": "uint256"
}
],
"internalType": "struct ISignatureTransfer.TokenPermissions"
},
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
}
],
"internalType": "struct ISignatureTransfer.PermitTransferFrom"
},
{
"name": "sig",
"type": "bytes",
"internalType": "bytes"
}
],
"outputs": [
{
"name": "positionData",
"type": "bytes",
"internalType": "bytes"
}
],
"stateMutability": "nonpayable"
},
{
"name": "approvedAdapters",
"type": "function",
"inputs": [
{
"name": "",
"type": "address",
"internalType": "address"
}
],
"outputs": [
{
"name": "",
"type": "bool",
"internalType": "bool"
}
],
"stateMutability": "view"
},
{
"name": "buy",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "indexSet",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "investmentAmount",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "minOutcomeTokensToBuy",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "maxFeeBps",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "auth",
"type": "tuple",
"components": [
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "signature",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.VenueAuth"
}
],
"outputs": [
{
"name": "outcomeTokensBought",
"type": "uint256",
"internalType": "uint256"
}
],
"stateMutability": "payable"
},
{
"name": "buyWithPermit2",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "indexSet",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "investmentAmount",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "minOutcomeTokensToBuy",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "maxFeeBps",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "auth",
"type": "tuple",
"components": [
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "signature",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.VenueAuth"
},
{
"name": "permit",
"type": "tuple",
"components": [
{
"name": "permitted",
"type": "tuple",
"components": [
{
"name": "token",
"type": "address",
"internalType": "address"
},
{
"name": "amount",
"type": "uint256",
"internalType": "uint256"
}
],
"internalType": "struct ISignatureTransfer.TokenPermissions"
},
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
}
],
"internalType": "struct ISignatureTransfer.PermitTransferFrom"
},
{
"name": "sig",
"type": "bytes",
"internalType": "bytes"
}
],
"outputs": [
{
"name": "outcomeTokensBought",
"type": "uint256",
"internalType": "uint256"
}
],
"stateMutability": "nonpayable"
},
{
"name": "claimFees",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "conditionIds",
"type": "bytes32[]",
"internalType": "bytes32[]"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "claimFeesFor",
"type": "function",
"inputs": [
{
"name": "owner",
"type": "address",
"internalType": "address"
},
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "sig",
"type": "bytes",
"internalType": "bytes"
},
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "conditionIds",
"type": "bytes32[]",
"internalType": "bytes32[]"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "claimFeesNonceUsed",
"type": "function",
"inputs": [
{
"name": "",
"type": "address",
"internalType": "address"
},
{
"name": "",
"type": "uint256",
"internalType": "uint256"
}
],
"outputs": [
{
"name": "",
"type": "bool",
"internalType": "bool"
}
],
"stateMutability": "view"
},
{
"name": "conditionIdFor",
"type": "function",
"inputs": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "outcomeSlotCount",
"type": "uint8",
"internalType": "uint8"
},
{
"name": "marketIndex",
"type": "uint256",
"internalType": "uint256"
}
],
"outputs": [
{
"name": "",
"type": "bytes32",
"internalType": "bytes32"
}
],
"stateMutability": "view"
},
{
"name": "conditionIdsForOracleQuestion",
"type": "function",
"inputs": [
{
"name": "",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "",
"type": "uint256",
"internalType": "uint256"
}
],
"outputs": [
{
"name": "",
"type": "bytes32",
"internalType": "bytes32"
}
],
"stateMutability": "view"
},
{
"name": "createMarket",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "p",
"type": "tuple",
"components": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "oracleAdapter",
"type": "address",
"internalType": "contract IOracleAdapter"
},
{
"name": "collateral",
"type": "address",
"internalType": "contract IERC20"
},
{
"name": "fee",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingStart",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingClose",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "voidPolicy",
"type": "uint8",
"internalType": "enum PredictionMarketCore.VoidPolicy"
},
{
"name": "creatorFeeBps",
"type": "uint16",
"internalType": "uint16"
},
{
"name": "metadata",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.CreateMarketParams"
},
{
"name": "auth",
"type": "tuple",
"components": [
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "signature",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.VenueAuth"
}
],
"outputs": [
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "market",
"type": "address",
"internalType": "address"
}
],
"stateMutability": "nonpayable"
},
{
"name": "createMarket",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "p",
"type": "tuple",
"components": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "oracleAdapter",
"type": "address",
"internalType": "contract IOracleAdapter"
},
{
"name": "collateral",
"type": "address",
"internalType": "contract IERC20"
},
{
"name": "fee",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingStart",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingClose",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "voidPolicy",
"type": "uint8",
"internalType": "enum PredictionMarketCore.VoidPolicy"
},
{
"name": "creatorFeeBps",
"type": "uint16",
"internalType": "uint16"
}
],
"internalType": "struct PredictionMarketCore.LegacyCreateMarketParams"
},
{
"name": "auth",
"type": "tuple",
"components": [
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "signature",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.VenueAuth"
}
],
"outputs": [
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "market",
"type": "address",
"internalType": "address"
}
],
"stateMutability": "nonpayable"
},
{
"name": "createMarketAndSeed",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "p",
"type": "tuple",
"components": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "oracleAdapter",
"type": "address",
"internalType": "contract IOracleAdapter"
},
{
"name": "collateral",
"type": "address",
"internalType": "contract IERC20"
},
{
"name": "fee",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingStart",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingClose",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "voidPolicy",
"type": "uint8",
"internalType": "enum PredictionMarketCore.VoidPolicy"
},
{
"name": "creatorFeeBps",
"type": "uint16",
"internalType": "uint16"
},
{
"name": "metadata",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.CreateMarketParams"
},
{
"name": "initialFunding",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "context",
"type": "bytes",
"internalType": "bytes"
},
{
"name": "auth",
"type": "tuple",
"components": [
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "signature",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.VenueAuth"
}
],
"outputs": [
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "market",
"type": "address",
"internalType": "address"
},
{
"name": "positionData",
"type": "bytes",
"internalType": "bytes"
}
],
"stateMutability": "nonpayable"
},
{
"name": "createMarketAndSeed",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "p",
"type": "tuple",
"components": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "oracleAdapter",
"type": "address",
"internalType": "contract IOracleAdapter"
},
{
"name": "collateral",
"type": "address",
"internalType": "contract IERC20"
},
{
"name": "fee",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingStart",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingClose",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "voidPolicy",
"type": "uint8",
"internalType": "enum PredictionMarketCore.VoidPolicy"
},
{
"name": "creatorFeeBps",
"type": "uint16",
"internalType": "uint16"
}
],
"internalType": "struct PredictionMarketCore.LegacyCreateMarketParams"
},
{
"name": "initialFunding",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "context",
"type": "bytes",
"internalType": "bytes"
},
{
"name": "auth",
"type": "tuple",
"components": [
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "signature",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.VenueAuth"
}
],
"outputs": [
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "market",
"type": "address",
"internalType": "address"
},
{
"name": "positionData",
"type": "bytes",
"internalType": "bytes"
}
],
"stateMutability": "nonpayable"
},
{
"name": "eip712Domain",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "fields",
"type": "bytes1",
"internalType": "bytes1"
},
{
"name": "name",
"type": "string",
"internalType": "string"
},
{
"name": "version",
"type": "string",
"internalType": "string"
},
{
"name": "chainId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "verifyingContract",
"type": "address",
"internalType": "address"
},
{
"name": "salt",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "extensions",
"type": "uint256[]",
"internalType": "uint256[]"
}
],
"stateMutability": "view"
},
{
"name": "initialize",
"type": "function",
"inputs": [
{
"name": "conditionalTokens_",
"type": "address",
"internalType": "contract ConditionalTokens"
},
{
"name": "orderRouter_",
"type": "address",
"internalType": "contract OrderRouter"
},
{
"name": "venueRegistry_",
"type": "address",
"internalType": "contract VenueRegistry"
},
{
"name": "wNative_",
"type": "address",
"internalType": "contract IWETH9"
},
{
"name": "admin_",
"type": "address",
"internalType": "address"
},
{
"name": "permit2_",
"type": "address",
"internalType": "address"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "marketAddress",
"type": "function",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
}
],
"outputs": [
{
"name": "market",
"type": "address",
"internalType": "address"
}
],
"stateMutability": "view"
},
{
"name": "marketCountFor",
"type": "function",
"inputs": [
{
"name": "",
"type": "uint256",
"internalType": "uint256"
}
],
"outputs": [
{
"name": "",
"type": "uint256",
"internalType": "uint256"
}
],
"stateMutability": "view"
},
{
"name": "markets",
"type": "function",
"inputs": [
{
"name": "",
"type": "bytes32",
"internalType": "bytes32"
}
],
"outputs": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "questionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "outcomeSlotCount",
"type": "uint8",
"internalType": "uint8"
},
{
"name": "voidPolicy",
"type": "uint8",
"internalType": "enum PredictionMarketCore.VoidPolicy"
},
{
"name": "collateralToken",
"type": "address",
"internalType": "contract IERC20"
},
{
"name": "fee",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "_deprecatedExpectedResolutionTime",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "originVenueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "oracleAdapter",
"type": "address",
"internalType": "contract IOracleAdapter"
},
{
"name": "creator",
"type": "address",
"internalType": "address"
},
{
"name": "creatorFeeBps",
"type": "uint16",
"internalType": "uint16"
},
{
"name": "market",
"type": "address",
"internalType": "address"
},
{
"name": "tradingClose",
"type": "uint64",
"internalType": "uint64"
},
{
"name": "metadata",
"type": "bytes",
"internalType": "bytes"
}
],
"stateMutability": "view"
},
{
"name": "mergeCompleteSet",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "amount",
"type": "uint256",
"internalType": "uint256"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "mintCompleteSet",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "amount",
"type": "uint256",
"internalType": "uint256"
}
],
"outputs": [],
"stateMutability": "payable"
},
{
"name": "multicall",
"type": "function",
"inputs": [
{
"name": "data",
"type": "bytes[]",
"internalType": "bytes[]"
}
],
"outputs": [
{
"name": "results",
"type": "bytes[]",
"internalType": "bytes[]"
}
],
"stateMutability": "nonpayable"
},
{
"name": "onERC1155BatchReceived",
"type": "function",
"inputs": [
{
"name": "",
"type": "address",
"internalType": "address"
},
{
"name": "",
"type": "address",
"internalType": "address"
},
{
"name": "",
"type": "uint256[]",
"internalType": "uint256[]"
},
{
"name": "",
"type": "uint256[]",
"internalType": "uint256[]"
},
{
"name": "",
"type": "bytes",
"internalType": "bytes"
}
],
"outputs": [
{
"name": "",
"type": "bytes4",
"internalType": "bytes4"
}
],
"stateMutability": "nonpayable"
},
{
"name": "onERC1155Received",
"type": "function",
"inputs": [
{
"name": "",
"type": "address",
"internalType": "address"
},
{
"name": "",
"type": "address",
"internalType": "address"
},
{
"name": "",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "",
"type": "bytes",
"internalType": "bytes"
}
],
"outputs": [
{
"name": "",
"type": "bytes4",
"internalType": "bytes4"
}
],
"stateMutability": "nonpayable"
},
{
"name": "onOracleAnswer",
"type": "function",
"inputs": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "outcomeIdx",
"type": "uint8",
"internalType": "uint8"
},
{
"name": "voided",
"type": "bool",
"internalType": "bool"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "owner",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "",
"type": "address",
"internalType": "address"
}
],
"stateMutability": "view"
},
{
"name": "pendingOwner",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "",
"type": "address",
"internalType": "address"
}
],
"stateMutability": "view"
},
{
"name": "pokeOracle",
"type": "function",
"inputs": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "proxiableUUID",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "",
"type": "bytes32",
"internalType": "bytes32"
}
],
"stateMutability": "view"
},
{
"name": "quoteBuy",
"type": "function",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "indexSet",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "investmentAmount",
"type": "uint256",
"internalType": "uint256"
}
],
"outputs": [
{
"name": "",
"type": "uint256",
"internalType": "uint256"
}
],
"stateMutability": "view"
},
{
"name": "quoteBuyFull",
"type": "function",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "indexSet",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "investmentAmount",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "routingVenueId",
"type": "uint32",
"internalType": "uint32"
}
],
"outputs": [
{
"name": "",
"type": "uint256",
"internalType": "uint256"
}
],
"stateMutability": "view"
},
{
"name": "quoteSell",
"type": "function",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "outcomeIndex",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "returnAmount",
"type": "uint256",
"internalType": "uint256"
}
],
"outputs": [
{
"name": "",
"type": "uint256",
"internalType": "uint256"
}
],
"stateMutability": "view"
},
{
"name": "redeem",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "indexSets",
"type": "uint256[]",
"internalType": "uint256[]"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "redeemFor",
"type": "function",
"inputs": [
{
"name": "owner",
"type": "address",
"internalType": "address"
},
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "sig",
"type": "bytes",
"internalType": "bytes"
},
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "indexSets",
"type": "uint256[]",
"internalType": "uint256[]"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "redeemNonceUsed",
"type": "function",
"inputs": [
{
"name": "",
"type": "address",
"internalType": "address"
},
{
"name": "",
"type": "uint256",
"internalType": "uint256"
}
],
"outputs": [
{
"name": "",
"type": "bool",
"internalType": "bool"
}
],
"stateMutability": "view"
},
{
"name": "removeLiquidity",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "positionData",
"type": "bytes",
"internalType": "bytes"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "renounceOwnership",
"type": "function",
"inputs": [],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "scheduleAndCreateMarket",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "adapter",
"type": "address",
"internalType": "contract IOracleAdapter"
},
{
"name": "def",
"type": "tuple",
"components": [
{
"name": "questionText",
"type": "string",
"internalType": "string"
},
{
"name": "sources",
"type": "tuple[]",
"components": [
{
"name": "sourceType",
"type": "uint8",
"internalType": "enum QuestionSourceType"
},
{
"name": "params",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct QuestionSource[]"
},
{
"name": "validAnswers",
"type": "tuple",
"components": [
{
"name": "answerType",
"type": "uint8",
"internalType": "enum AnswerType"
},
{
"name": "discreteOutcomes",
"type": "string[]",
"internalType": "string[]"
},
{
"name": "numericIntervals",
"type": "tuple[]",
"components": [
{
"name": "low",
"type": "int256",
"internalType": "int256"
},
{
"name": "high",
"type": "int256",
"internalType": "int256"
}
],
"internalType": "struct Interval[]"
},
{
"name": "numericDecimals",
"type": "uint64",
"internalType": "uint64"
}
],
"internalType": "struct ValidAnswers"
},
{
"name": "resolutionTime",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "minAgreement",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "subcommitteeSize",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "subcommitteeThreshold",
"type": "uint256",
"internalType": "uint256"
}
],
"internalType": "struct QuestionDefinition"
},
{
"name": "p",
"type": "tuple",
"components": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "oracleAdapter",
"type": "address",
"internalType": "contract IOracleAdapter"
},
{
"name": "collateral",
"type": "address",
"internalType": "contract IERC20"
},
{
"name": "fee",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingStart",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingClose",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "voidPolicy",
"type": "uint8",
"internalType": "enum PredictionMarketCore.VoidPolicy"
},
{
"name": "creatorFeeBps",
"type": "uint16",
"internalType": "uint16"
},
{
"name": "metadata",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.CreateMarketParams"
},
{
"name": "auth",
"type": "tuple",
"components": [
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "signature",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.VenueAuth"
}
],
"outputs": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "market",
"type": "address",
"internalType": "address"
}
],
"stateMutability": "payable"
},
{
"name": "scheduleAndCreateMarket",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "adapter",
"type": "address",
"internalType": "contract IOracleAdapter"
},
{
"name": "def",
"type": "tuple",
"components": [
{
"name": "questionText",
"type": "string",
"internalType": "string"
},
{
"name": "sources",
"type": "tuple[]",
"components": [
{
"name": "sourceType",
"type": "uint8",
"internalType": "enum QuestionSourceType"
},
{
"name": "params",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct QuestionSource[]"
},
{
"name": "validAnswers",
"type": "tuple",
"components": [
{
"name": "answerType",
"type": "uint8",
"internalType": "enum AnswerType"
},
{
"name": "discreteOutcomes",
"type": "string[]",
"internalType": "string[]"
},
{
"name": "numericIntervals",
"type": "tuple[]",
"components": [
{
"name": "low",
"type": "int256",
"internalType": "int256"
},
{
"name": "high",
"type": "int256",
"internalType": "int256"
}
],
"internalType": "struct Interval[]"
},
{
"name": "numericDecimals",
"type": "uint64",
"internalType": "uint64"
}
],
"internalType": "struct ValidAnswers"
},
{
"name": "resolutionTime",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "minAgreement",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "subcommitteeSize",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "subcommitteeThreshold",
"type": "uint256",
"internalType": "uint256"
}
],
"internalType": "struct QuestionDefinition"
},
{
"name": "p",
"type": "tuple",
"components": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "oracleAdapter",
"type": "address",
"internalType": "contract IOracleAdapter"
},
{
"name": "collateral",
"type": "address",
"internalType": "contract IERC20"
},
{
"name": "fee",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingStart",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingClose",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "voidPolicy",
"type": "uint8",
"internalType": "enum PredictionMarketCore.VoidPolicy"
},
{
"name": "creatorFeeBps",
"type": "uint16",
"internalType": "uint16"
}
],
"internalType": "struct PredictionMarketCore.LegacyCreateMarketParams"
},
{
"name": "auth",
"type": "tuple",
"components": [
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "signature",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.VenueAuth"
}
],
"outputs": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "market",
"type": "address",
"internalType": "address"
}
],
"stateMutability": "payable"
},
{
"name": "scheduleCreateAndSeed",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "adapter",
"type": "address",
"internalType": "contract IOracleAdapter"
},
{
"name": "def",
"type": "tuple",
"components": [
{
"name": "questionText",
"type": "string",
"internalType": "string"
},
{
"name": "sources",
"type": "tuple[]",
"components": [
{
"name": "sourceType",
"type": "uint8",
"internalType": "enum QuestionSourceType"
},
{
"name": "params",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct QuestionSource[]"
},
{
"name": "validAnswers",
"type": "tuple",
"components": [
{
"name": "answerType",
"type": "uint8",
"internalType": "enum AnswerType"
},
{
"name": "discreteOutcomes",
"type": "string[]",
"internalType": "string[]"
},
{
"name": "numericIntervals",
"type": "tuple[]",
"components": [
{
"name": "low",
"type": "int256",
"internalType": "int256"
},
{
"name": "high",
"type": "int256",
"internalType": "int256"
}
],
"internalType": "struct Interval[]"
},
{
"name": "numericDecimals",
"type": "uint64",
"internalType": "uint64"
}
],
"internalType": "struct ValidAnswers"
},
{
"name": "resolutionTime",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "minAgreement",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "subcommitteeSize",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "subcommitteeThreshold",
"type": "uint256",
"internalType": "uint256"
}
],
"internalType": "struct QuestionDefinition"
},
{
"name": "p",
"type": "tuple",
"components": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "oracleAdapter",
"type": "address",
"internalType": "contract IOracleAdapter"
},
{
"name": "collateral",
"type": "address",
"internalType": "contract IERC20"
},
{
"name": "fee",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingStart",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingClose",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "voidPolicy",
"type": "uint8",
"internalType": "enum PredictionMarketCore.VoidPolicy"
},
{
"name": "creatorFeeBps",
"type": "uint16",
"internalType": "uint16"
}
],
"internalType": "struct PredictionMarketCore.LegacyCreateMarketParams"
},
{
"name": "initialFunding",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "context",
"type": "bytes",
"internalType": "bytes"
},
{
"name": "auth",
"type": "tuple",
"components": [
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "signature",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.VenueAuth"
}
],
"outputs": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "market",
"type": "address",
"internalType": "address"
},
{
"name": "positionData",
"type": "bytes",
"internalType": "bytes"
}
],
"stateMutability": "payable"
},
{
"name": "scheduleCreateAndSeed",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "adapter",
"type": "address",
"internalType": "contract IOracleAdapter"
},
{
"name": "def",
"type": "tuple",
"components": [
{
"name": "questionText",
"type": "string",
"internalType": "string"
},
{
"name": "sources",
"type": "tuple[]",
"components": [
{
"name": "sourceType",
"type": "uint8",
"internalType": "enum QuestionSourceType"
},
{
"name": "params",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct QuestionSource[]"
},
{
"name": "validAnswers",
"type": "tuple",
"components": [
{
"name": "answerType",
"type": "uint8",
"internalType": "enum AnswerType"
},
{
"name": "discreteOutcomes",
"type": "string[]",
"internalType": "string[]"
},
{
"name": "numericIntervals",
"type": "tuple[]",
"components": [
{
"name": "low",
"type": "int256",
"internalType": "int256"
},
{
"name": "high",
"type": "int256",
"internalType": "int256"
}
],
"internalType": "struct Interval[]"
},
{
"name": "numericDecimals",
"type": "uint64",
"internalType": "uint64"
}
],
"internalType": "struct ValidAnswers"
},
{
"name": "resolutionTime",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "minAgreement",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "subcommitteeSize",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "subcommitteeThreshold",
"type": "uint256",
"internalType": "uint256"
}
],
"internalType": "struct QuestionDefinition"
},
{
"name": "p",
"type": "tuple",
"components": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "oracleAdapter",
"type": "address",
"internalType": "contract IOracleAdapter"
},
{
"name": "collateral",
"type": "address",
"internalType": "contract IERC20"
},
{
"name": "fee",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingStart",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "tradingClose",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "voidPolicy",
"type": "uint8",
"internalType": "enum PredictionMarketCore.VoidPolicy"
},
{
"name": "creatorFeeBps",
"type": "uint16",
"internalType": "uint16"
},
{
"name": "metadata",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.CreateMarketParams"
},
{
"name": "initialFunding",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "context",
"type": "bytes",
"internalType": "bytes"
},
{
"name": "auth",
"type": "tuple",
"components": [
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "signature",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.VenueAuth"
}
],
"outputs": [
{
"name": "oracleQuestionId",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "market",
"type": "address",
"internalType": "address"
},
{
"name": "positionData",
"type": "bytes",
"internalType": "bytes"
}
],
"stateMutability": "payable"
},
{
"name": "sell",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "outcomeIndex",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "returnAmount",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "maxOutcomeTokensToSell",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "maxFeeBps",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "auth",
"type": "tuple",
"components": [
{
"name": "nonce",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "deadline",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "signature",
"type": "bytes",
"internalType": "bytes"
}
],
"internalType": "struct PredictionMarketCore.VenueAuth"
}
],
"outputs": [
{
"name": "outcomeTokensSold",
"type": "uint256",
"internalType": "uint256"
}
],
"stateMutability": "nonpayable"
},
{
"name": "setAdapterApproved",
"type": "function",
"inputs": [
{
"name": "adapter",
"type": "address",
"internalType": "address"
},
{
"name": "approved",
"type": "bool",
"internalType": "bool"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "setTradingStart",
"type": "function",
"inputs": [
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
},
{
"name": "newTradingStart",
"type": "uint64",
"internalType": "uint64"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "supportsInterface",
"type": "function",
"inputs": [
{
"name": "interfaceId",
"type": "bytes4",
"internalType": "bytes4"
}
],
"outputs": [
{
"name": "",
"type": "bool",
"internalType": "bool"
}
],
"stateMutability": "view"
},
{
"name": "sweepERC20",
"type": "function",
"inputs": [
{
"name": "token",
"type": "address",
"internalType": "contract IERC20"
},
{
"name": "to",
"type": "address",
"internalType": "address"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "transferOwnership",
"type": "function",
"inputs": [
{
"name": "newOwner",
"type": "address",
"internalType": "address"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "upgradeToAndCall",
"type": "function",
"inputs": [
{
"name": "newImplementation",
"type": "address",
"internalType": "address"
},
{
"name": "data",
"type": "bytes",
"internalType": "bytes"
}
],
"outputs": [],
"stateMutability": "payable"
},
{
"name": "venueNonceUsed",
"type": "function",
"inputs": [
{
"name": "",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "",
"type": "address",
"internalType": "address"
},
{
"name": "",
"type": "uint256",
"internalType": "uint256"
}
],
"outputs": [
{
"name": "",
"type": "bool",
"internalType": "bool"
}
],
"stateMutability": "view"
},
{
"name": "wNative",
"type": "function",
"inputs": [],
"outputs": [
{
"name": "",
"type": "address",
"internalType": "contract IWETH9"
}
],
"stateMutability": "view"
},
{
"name": "withdraw",
"type": "function",
"inputs": [
{
"name": "amount",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "to",
"type": "address",
"internalType": "address payable"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"name": "withdrawFees",
"type": "function",
"inputs": [
{
"name": "venueId",
"type": "uint32",
"internalType": "uint32"
},
{
"name": "conditionId",
"type": "bytes32",
"internalType": "bytes32"
}
],
"outputs": [],
"stateMutability": "nonpayable"
},
{
"type": "receive",
"stateMutability": "payable"
}
]