# MarketFactory

Market factory is used to create prediction markets of different types.

Market creation logic:

1. Ask reality questions.
2. Prepare condition.
3. Create new erc20 outcome tokens.
4. Initialize a new market contract.

## Variables

### CreateMarketParams

_Workaround "stack too deep" errors._

```solidity
struct CreateMarketParams {
  string marketName;
  string[] outcomes;
  string questionStart;
  string questionEnd;
  string outcomeType;
  uint256 parentOutcome;
  address parentMarket;
  string category;
  string lang;
  uint256 lowerBound;
  uint256 upperBound;
  uint256 minBond;
  uint32 openingTime;
  string[] tokenNames;
}
```

### InternalMarketConfig

_Workaround "stack too deep" errors._

```solidity
struct InternalMarketConfig {
  string[] encodedQuestions;
  uint256 outcomeSlotCount;
  uint256 templateId;
}
```

### REALITY\_UINT\_TEMPLATE

```solidity
uint8 REALITY_UINT_TEMPLATE
```

_Template for scalar and multi scalar markets._

### REALITY\_SINGLE\_SELECT\_TEMPLATE

```solidity
uint8 REALITY_SINGLE_SELECT_TEMPLATE
```

_Template for categorical markets._

### REALITY\_MULTI\_SELECT\_TEMPLATE

```solidity
uint8 REALITY_MULTI_SELECT_TEMPLATE
```

_Template for multi categorical markets._

### questionTimeout

```solidity
uint32 questionTimeout
```

_Reality question timeout._

### arbitrator

```solidity
address arbitrator
```

_Arbitrator contract._

### realitio

```solidity
contract IRealityETH_v3_0 realitio
```

_Reality.eth contract._

### wrapped1155Factory

```solidity
contract IWrapped1155Factory wrapped1155Factory
```

_Wrapped1155Factory contract._

### conditionalTokens

```solidity
contract IConditionalTokens conditionalTokens
```

_Conditional Tokens contract._

### collateralToken

```solidity
address collateralToken
```

_Conditional Tokens collateral token contract._

### realityProxy

```solidity
contract RealityProxy realityProxy
```

_Oracle contract._

### markets

```solidity
address[] markets
```

_Markets created by this factory._

### market

```solidity
address market
```

_Market contract._

## Events

### NewMarket

```solidity
event NewMarket(address market, string marketName, address parentMarket, bytes32 conditionId, bytes32 questionId, bytes32[] questionsIds)
```

_To be emitted when a new market is created._

**Parameters**

| Name         | Type       | Description                     |
| ------------ | ---------- | ------------------------------- |
| market       | address    | The new market address.         |
| marketName   | string     | The name of the market.         |
| parentMarket | address    | Conditional market to use.      |
| conditionId  | bytes32    | Conditional Tokens conditionId. |
| questionId   | bytes32    | Conditional Tokens questionId.  |
| questionsIds | bytes32\[] | Reality questions ids.          |

## Functions

### constructor

```solidity
constructor(address _market, address _arbitrator, contract IRealityETH_v3_0 _realitio, contract IWrapped1155Factory _wrapped1155Factory, contract IConditionalTokens _conditionalTokens, address _collateralToken, contract RealityProxy _realityProxy, uint32 _questionTimeout) public
```

_Constructor._

| Name                 | Type                         | Description                                                                      |
| -------------------- | ---------------------------- | -------------------------------------------------------------------------------- |
| \_market             | address                      | Address of the market contract that is going to be used for each new deployment. |
| \_arbitrator         | address                      | Address of the arbitrator that is going to resolve Realitio disputes.            |
| \_realitio           | contract IRealityETH\_v3\_0  | Address of the Realitio implementation.                                          |
| \_wrapped1155Factory | contract IWrapped1155Factory | Address of the Wrapped1155Factory implementation.                                |
| \_conditionalTokens  | contract IConditionalTokens  | Address of the ConditionalTokens implementation.                                 |
| \_collateralToken    | address                      | Address of the collateral token.                                                 |
| \_realityProxy       | contract RealityProxy        | Address of the RealityProxy implementation.                                      |
| \_questionTimeout    | uint32                       | Reality question timeout.                                                        |

### createCategoricalMarket

```solidity
function createCategoricalMarket(struct MarketFactory.CreateMarketParams params) external returns (address)
```

Categorical markets are associated with a Reality question that has only one answer.

_Creates a Categorical market._

**Parameters**

| Name   | Type                                    | Description                  |
| ------ | --------------------------------------- | ---------------------------- |
| params | struct MarketFactory.CreateMarketParams | CreateMarketParams instance. |

**Return Values**

| Name | Type    | Description             |
| ---- | ------- | ----------------------- |
| \[0] | address | The new market address. |

**Logic**

1. Validate outcomes length (>= 2).
2. Encode 1 reality question.
3. Call <mark style="color:red;">`createMarket`</mark>.

### createMultiCategoricalMarket

```solidity
function createMultiCategoricalMarket(struct MarketFactory.CreateMarketParams params) external returns (address)
```

Multi Categorical markets are associated with a Reality question that has one or more answers.

_Creates a Multi Categorical market._

**Parameters**

| Name   | Type                                    | Description                  |
| ------ | --------------------------------------- | ---------------------------- |
| params | struct MarketFactory.CreateMarketParams | CreateMarketParams instance. |

**Return Values**

| Name | Type    | Description             |
| ---- | ------- | ----------------------- |
| \[0] | address | The new market address. |

**Logic**

1. Validate outcomes length (>=2).
2. Encode 1 reality question.
3. Call <mark style="color:red;">`createMarket`</mark>.

### createScalarMarket

```solidity
function createScalarMarket(struct MarketFactory.CreateMarketParams params) external returns (address)
```

Scalar markets are associated with a Reality question that resolves to a numeric value.

_Creates a Scalar market._

**Parameters**

| Name   | Type                                    | Description                  |
| ------ | --------------------------------------- | ---------------------------- |
| params | struct MarketFactory.CreateMarketParams | CreateMarketParams instance. |

**Return Values**

| Name | Type    | Description             |
| ---- | ------- | ----------------------- |
| \[0] | address | The new market address. |

**Logic**

1. Validate <mark style="color:red;">`upperBound`</mark> and <mark style="color:red;">`lowerBound`</mark>.
2. Validate outcomes length (2).
3. Encode 1 reality question.
4. Call <mark style="color:red;">`createMarket`</mark>.

### createMultiScalarMarket

```solidity
function createMultiScalarMarket(struct MarketFactory.CreateMarketParams params) external returns (address)
```

Multi Scalar markets are associated with two or more Reality questions, and each one of them resolves to a numeric value.

_Creates a Multi Scalar market._

**Parameters**

| Name   | Type                                    | Description                  |
| ------ | --------------------------------------- | ---------------------------- |
| params | struct MarketFactory.CreateMarketParams | CreateMarketParams instance. |

**Return Values**

| Name | Type    | Description             |
| ---- | ------- | ----------------------- |
| \[0] | address | The new market address. |

**Logic**

1. Validate outcomes length (>=2).
2. Encode reality questions, one for each outcome.
3.  Instead of using <mark style="color:red;">`params.marketName`</mark>, encode a new <mark style="color:red;">`marketName`</mark>.

    ```solidity
    abi.encodePacked(
        params.questionStart,
        "[",
        params.outcomeType,
        "]",
        params.questionEnd
    )
    ```
4. Call <mark style="color:red;">`createMarket`</mark>.

### createMarket

```solidity
function createMarket(struct MarketFactory.CreateMarketParams params, string marketName, struct MarketFactory.InternalMarketConfig config) internal returns (address)
```

_Creates the Market and deploys the wrapped ERC20 tokens._

**Parameters**

| Name       | Type                                      | Description                    |
| ---------- | ----------------------------------------- | ------------------------------ |
| params     | struct MarketFactory.CreateMarketParams   | CreateMarketParams instance.   |
| marketName | string                                    | The market name.               |
| config     | struct MarketFactory.InternalMarketConfig | InternalMarketConfig instance. |

**Return Values**

| Name | Type    | Description             |
| ---- | ------- | ----------------------- |
| \[0] | address | The new market address. |

**Logic**

1. Ask reality questions.
2. Prepare condition.
3. Create new erc20 outcome tokens.
4. Initialize a new market contract.

### createNewMarketParams

```solidity
function createNewMarketParams(struct MarketFactory.CreateMarketParams params, struct MarketFactory.InternalMarketConfig config) internal returns (struct Market.ConditionalTokensParams, struct Market.RealityParams)
```

_Creates the structures needed to initialize the new market._

**Parameters**

| Name   | Type                                      | Description                    |
| ------ | ----------------------------------------- | ------------------------------ |
| params | struct MarketFactory.CreateMarketParams   | CreateMarketParams instance.   |
| config | struct MarketFactory.InternalMarketConfig | InternalMarketConfig instance. |

**Return Values**

| Name | Type                                  | Description                              |
| ---- | ------------------------------------- | ---------------------------------------- |
| \[0] | struct Market.ConditionalTokensParams | Market.ConditionalTokensParams instance. |
| \[1] | struct Market.RealityParams           | Market.RealityParams instance.           |

### encodeRealityQuestionWithOutcomes

```solidity
function encodeRealityQuestionWithOutcomes(string question, string[] outcomes, string category, string lang) internal pure returns (string)
```

_Encodes the question, outcomes, category and language following the Reality structure. If any parameter has a special character like quotes, it must be properly escaped._

**Parameters**

| Name     | Type      | Description            |
| -------- | --------- | ---------------------- |
| question | string    | The question text.     |
| outcomes | string\[] |                        |
| category | string    | The question category. |
| lang     | string    | The question language. |

**Return Values**

| Name | Type   | Description           |
| ---- | ------ | --------------------- |
| \[0] | string | The encoded question. |

### encodeRealityQuestionWithoutOutcomes

```solidity
function encodeRealityQuestionWithoutOutcomes(string question, string category, string lang) internal pure returns (string)
```

_Encodes the question, category and language following the Reality structure. If any parameter has a special character like quotes, it must be properly escaped._

**Parameters**

| Name     | Type   | Description            |
| -------- | ------ | ---------------------- |
| question | string | The question text.     |
| category | string | The question category. |
| lang     | string | The question language. |

**Return Values**

| Name | Type   | Description           |
| ---- | ------ | --------------------- |
| \[0] | string | The encoded question. |

### askRealityQuestion

```solidity
function askRealityQuestion(string encodedQuestion, uint256 templateId, uint32 openingTime, uint256 minBond) internal returns (bytes32)
```

_Asks a question on reality._

**Parameters**

| Name            | Type    | Description                                             |
| --------------- | ------- | ------------------------------------------------------- |
| encodedQuestion | string  | The encoded question containing the Reality parameters. |
| templateId      | uint256 | The Reality template id.                                |
| openingTime     | uint32  | The question opening time.                              |
| minBond         | uint256 | The question min bond.                                  |

**Return Values**

| Name | Type    | Description     |
| ---- | ------- | --------------- |
| \[0] | bytes32 | The question id |

### prepareCondition

```solidity
function prepareCondition(bytes32 questionId, uint256 outcomeSlotCount) internal returns (bytes32)
```

_Prepares the CTF condition and returns the conditionId._

**Parameters**

| Name             | Type    | Description                                                                             |
| ---------------- | ------- | --------------------------------------------------------------------------------------- |
| questionId       | bytes32 | An identifier for the question to be answered by the oracle.                            |
| outcomeSlotCount | uint256 | The number of outcome slots which must be used for this condition. Must not exceed 256. |

**Return Values**

| Name | Type    | Description   |
| ---- | ------- | ------------- |
| \[0] | bytes32 | Condition ID. |

**Pre-condition**

1. Reality questions asked and return <mark style="color:red;">`questionsIds`</mark>.
2. <mark style="color:red;">`questionId`</mark> is hashed from all the values that <mark style="color:red;">`RealityProxy.resolve()`</mark> uses to resolve a market (<mark style="color:red;">`questionsIds`</mark>, <mark style="color:red;">`outcomes.length`</mark>, <mark style="color:red;">`templateId`</mark>, <mark style="color:red;">`lowerBound`</mark>, <mark style="color:red;">`upperBound`</mark>).

**Logic**

1. It will check if there is a prepared condition on <mark style="color:red;">`ConditionalTokens`</mark>, and call <mark style="color:red;">`conditionalTokens.prepareCondition()`</mark> if there isn't any.

### deployERC20Positions

```solidity
function deployERC20Positions(bytes32 parentCollectionId, bytes32 conditionId, uint256 outcomeSlotCount, string[] tokenNames) internal returns (contract IERC20[] wrapped1155, bytes[] data)
```

_Wraps the ERC1155 outcome tokens to ERC20. The INVALID\_RESULT outcome is always called SER-INVALID._

**Parameters**

| Name               | Type      | Description                     |
| ------------------ | --------- | ------------------------------- |
| parentCollectionId | bytes32   | The parentCollectionId.         |
| conditionId        | bytes32   | The conditionId.                |
| outcomeSlotCount   | uint256   | The amount of outcomes.         |
| tokenNames         | string\[] | The name of each outcome token. |

**Return Values**

| Name        | Type               | Description                                    |
| ----------- | ------------------ | ---------------------------------------------- |
| wrapped1155 | contract IERC20\[] | Array of outcome tokens wrapped to ERC20.      |
| data        | bytes\[]           | Array of token data used to create each ERC20. |

**Logic**

1. It will call <mark style="color:red;">`wrapped1155Factory.requireWrapped1155`</mark> to create an ERC20 token contract for each position. The new tokens addresses and data is saved in <mark style="color:red;">`Market`</mark> contract.

### toString31

```solidity
function toString31(string value) internal pure returns (bytes32 encodedString)
```

_Encodes a short string (less than than 31 bytes long) as for storage as expected by Solidity. See_ [_https://github.com/gnosis/1155-to-20/pull/4#discussion\_r573630922_](https://github.com/gnosis/1155-to-20/pull/4#discussion_r573630922)_._

**Parameters**

| Name  | Type   | Description      |
| ----- | ------ | ---------------- |
| value | string | String to encode |

**Return Values**

| Name          | Type    | Description         |
| ------------- | ------- | ------------------- |
| encodedString | bytes32 | The encoded string. |

### allMarkets

```solidity
function allMarkets() external view returns (address[])
```

_Returns all the markets created by this factory._

**Return Values**

| Name | Type       | Description                   |
| ---- | ---------- | ----------------------------- |
| \[0] | address\[] | The addresses of the markets. |

### marketCount

```solidity
function marketCount() external view returns (uint256)
```

Returns the amount of markets created by this factory.

**Return Values**

| Name | Type    | Description            |
| ---- | ------- | ---------------------- |
| \[0] | uint256 | The amount of markets. |
