> For the complete documentation index, see [llms.txt](https://docs.crystal.exchange/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.crystal.exchange/developer-resources/smart-contract-methods/crystal.md).

# Crystal

## Functions

### feeRecipient

```solidity
function feeRecipient() external view returns (address)
```

Recipient address of protocol fees.

#### Return Values

| Name    | Type      | Description                   |
| ------- | --------- | ----------------------------- |
| address | `address` | Address that receives the fee |

***

### feeCommission

```solidity
function feeCommission() external view returns (uint8)
```

Referrer’s commission rate

#### Return Values

| Name          | Type    | Description                                |
| ------------- | ------- | ------------------------------------------ |
| feeCommission | `uint8` | Global referrer commission rate in percent |

***

### userIdToAddress

```solidity
function userIdToAddress(uint256) external view returns (address)
```

Retrieves the wallet address associated with a specific user ID.

#### Parameters

| Name   | Type      | Description  |
| ------ | --------- | ------------ |
| userId | `uint256` | The `userId` |

#### Return Values

| Name | Type      | Description                                    |
| ---- | --------- | ---------------------------------------------- |
| user | `address` | The address associated with the given `userId` |

***

### addressToUserId

```solidity
function addressToUserId(address) external view returns (uint256)
```

Retrieves the numeric user ID that corresponds to a given wallet address.

#### Parameters

| Name | Type      | Description                                    |
| ---- | --------- | ---------------------------------------------- |
| user | `address` | The address for which to retrieve the `userId` |

#### Return Values

| Name   | Type      | Description                                 |
| ------ | --------- | ------------------------------------------- |
| userId | `uint256` | The numeric user ID corresponding to `user` |

***

### claimableRewards

```solidity
function claimableRewards(address, address) external view returns (uint256)
```

Returns accrued rewards for `(token, user)`; claim via `claimFees`

#### Parameters

| Name  | Type      | Description                                             |
| ----- | --------- | ------------------------------------------------------- |
| token | `address` | ERC-20 token (WETH for native) in which rewards accrue. |
| user  | `address` | Account whose claimable balance is queried.             |

#### Return Values

| Name   | Type      | Description                                       |
| ------ | --------- | ------------------------------------------------- |
| amount | `uint256` | Accrued but unclaimed rewards for `(token, user)` |

***

### latestUserId

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

Returns the most recently issued `userId`.

#### Return Values

| Name         | Type      | Description    |
| ------------ | --------- | -------------- |
| latestUserId | `uint256` | Numeric result |

***

### gov

```solidity
function gov() external view returns (address)
```

Returns the current governance address.

#### Return Values

| Name | Type      | Description                       |
| ---- | --------- | --------------------------------- |
| gov  | `address` | Current governance/admin address. |

***

### feeClaimDuration

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

Seconds to wait before an expired-fees queue can be executed.

#### Return Values

| Name     | Type      | Description                                                                   |
| -------- | --------- | ----------------------------------------------------------------------------- |
| duration | `uint256` | Delay (in seconds) required between queuing and executing expired fee claims. |

***

### getMarketByTokens

```solidity
function getMarketByTokens(address, address) external view returns (address)
```

*Looks up market address given an asset pair.* May return a `placeholder` address for launchpad tokens before graduation; not routable until migrated.

#### Parameters

| Name     | Type      | Description                    |
| -------- | --------- | ------------------------------ |
| assetIn  | `address` | Input asset (WETH for native)  |
| assetOut | `address` | Output asset (WETH for native) |

#### Return Values

| Name   | Type      | Description                                                                                      |
| ------ | --------- | ------------------------------------------------------------------------------------------------ |
| market | `address` | Market contract for the pair, `placeholder` for launchpad pairs pre-graduation, or zero if none. |

***

### marketToMarketId

```solidity
function marketToMarketId(address) external view returns (uint256)
```

Returns the numeric `marketId` for a market address.

#### Parameters

| Name   | Type      | Description       |
| ------ | --------- | ----------------- |
| market | `address` | Address parameter |

#### Return Values

| Name     | Type      | Description    |
| -------- | --------- | -------------- |
| marketId | `uint256` | Numeric result |

***

### marketIdToMarket

```solidity
function marketIdToMarket(uint256) external view returns (address)
```

Returns the market address for a numeric `marketId`.

#### Parameters

| Name     | Type      | Description        |
| -------- | --------- | ------------------ |
| marketId | `uint256` | Numeric market ID. |

#### Return Values

| Name   | Type      | Description              |
| ------ | --------- | ------------------------ |
| market | `address` | Market contract address. |

***

### isCanonicalDeployer

```solidity
function isCanonicalDeployer(address) external view returns (bool)
```

Flag: address is allowed to deploy **canonical** markets.

#### Parameters

| Name     | Type      | Description      |
| -------- | --------- | ---------------- |
| deployer | `address` | Address to check |

#### Return Values

| Name    | Type   | Description               |
| ------- | ------ | ------------------------- |
| allowed | `bool` | True if address qualifies |

***

### allMarkets

```solidity
function allMarkets(uint256) external view returns (address)
```

Paging accessor over all market addresses.

#### Parameters

| Name  | Type      | Description                              |
| ----- | --------- | ---------------------------------------- |
| index | `uint256` | Zero-based index into the markets array. |

#### Return Values

| Name   | Type      | Description                |
| ------ | --------- | -------------------------- |
| market | `address` | Market address at `index`. |

***

### parameters

```solidity
function parameters() external view returns (address, address, uint256, uint256, uint256, uint256, uint256)
```

Returns global `Parameters` tuple (quote/base, market id/type, scale, tick, max price).

#### Return Values

| Name        | Type      | Description                                       |
| ----------- | --------- | ------------------------------------------------- |
| quoteAsset  | `address` | Quote token for the market under construction.    |
| baseAsset   | `address` | Base token for the market under construction.     |
| marketId    | `uint256` | Numeric ID assigned for deterministic deployment. |
| marketType  | `uint256` | Pricing mode (e.g., linear/decimal/tiered).       |
| scaleFactor | `uint256` | Decimal scaling for price math.                   |
| tickSize    | `uint256` | Minimum price increment.                          |
| maxPrice    | `uint256` | Upper bound used to seed tick bitmaps.            |

***

### launchpadParams

```solidity
function launchpadParams() external view returns (uint112, uint256, uint256, uint256, uint256, uint256, uint256)
```

Returns global `LaunchpadParams` tuple (initial supply, fees/splits, graduated params).

#### Return Values

| Name                         | Type      | Description                                            |
| ---------------------------- | --------- | ------------------------------------------------------ |
| launchpadInitialNativeSupply | `uint112` | Initial virtual native liquidity.                      |
| launchpadFee                 | `uint256` | Fee factor (scaled base 100\_000) on launchpad trades. |
| launchpadCreatorFeeSplit     | `uint256` | Creator share of launchpad fees (percent)              |
| graduatedMinSize             | `uint256` | Min order size for the graduated market.               |
| graduatedTakerFee            | `uint256` | Taker fee after graduation                             |
| graduatedMakerRebate         | `uint256` | Maker rebate after graduation                          |
| graduatedCreatorFeeSplit     | `uint256` | Creator fee split post-graduation (percent)            |

***

### launchpadTokenToMarket

```solidity
function launchpadTokenToMarket(address) external view returns (uint112, uint112, uint256, address, address, uint88)
```

Returns the `LaunchpadMarket` tuple bound to a token (virtual reserves, k, creator/market addresses, timestamp).

#### Parameters

| Name  | Type      | Description               |
| ----- | --------- | ------------------------- |
| token | `address` | Launchpad token to query. |

#### Return Values

| Name                 | Type      | Description                                        |
| -------------------- | --------- | -------------------------------------------------- |
| virtualNativeReserve | `uint112` | Simulated native-side reserve.                     |
| virtualTokenReserve  | `uint112` | Simulated token-side reserve.                      |
| k                    | `uint256` | Constant product used for bonding curve.           |
| creator              | `address` | Token creator entitled to fee split.               |
| market               | `address` | Spot market address to migrate into on graduation. |
| createTimestamp      | `uint88`  | Launch time used for inactivity windows.           |

***

### allTokens

```solidity
function allTokens(uint256) external view returns (address)
```

Paging accessor over all launchpad-created tokens.

#### Parameters

| Name  | Type      | Description                                     |
| ----- | --------- | ----------------------------------------------- |
| index | `uint256` | Zero-based index into launchpad-created tokens. |

#### Return Values

| Name  | Type      | Description             |
| ----- | --------- | ----------------------- |
| token | `address` | oken address at `index` |

***

### weth

```solidity
function weth() external view returns (address)
```

Returns the canonical WETH address used by the router.

#### Return Values

| Name | Type      | Description                                           |
| ---- | --------- | ----------------------------------------------------- |
| weth | `address` | Canonical WETH contract used for wrapping/unwrapping. |

***

### eth

```solidity
function eth() external view returns (address)
```

Returns the placeholder/native ETH address constant.

#### Return Values

| Name | Type      | Description                                                |
| ---- | --------- | ---------------------------------------------------------- |
| eth  | `address` | Sentinel constant representing native ETH (`0xEeee…EEeE`). |

***

### allMarketsLength

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

Returns the number of deployed markets.

#### Return Values

| Name   | Type      | Description                                              |
| ------ | --------- | -------------------------------------------------------- |
| length | `uint256` | Total number of deployed markets stored in the registry. |

***

### getMarket

```solidity
function getMarket(address market) external view returns (MarketInfo)
```

*Retrieves stored market data* (book top, fees, reserves, etc.).

#### Parameters

| Name     | Type      | Description    |
| -------- | --------- | -------------- |
| `market` | `address` | Market address |

#### Return Values

| Name   | Type         | Description                                                                               |
| ------ | ------------ | ----------------------------------------------------------------------------------------- |
| `info` | `MarketInfo` | Struct containing live market data (quote/base, price bounds, fees, reserves, AMM state). |

***

### getDepositedBalance

```solidity
function getDepositedBalance(address user, address asset) external view returns (uint256, uint256, uint256)
```

Returns balances held by protocol for `user` in `asset`.

#### Parameters

| Name    | Type      | Description                                |
| ------- | --------- | ------------------------------------------ |
| `user`  | `address` | Account whose balances are queried.        |
| `asset` | `address` | Token address (use WETH sentinel for ETH). |

#### Return Values

| Name      | Type      | Description                                      |
| --------- | --------- | ------------------------------------------------ |
| total     | `uint256` | Total tokens held in protocol custody.           |
| available | `uint256` | Portion free for withdrawal or new orders.       |
| locked    | `uint256` | Portion reserved for active orders or liquidity. |

***

### getAllOrdersByCloid

```solidity
function getAllOrdersByCloid(address user, uint256 range) external view returns (uint256[], Order[])
```

Returns batched packed ids and decoded `Order[]` for a user’s CLOID bucket (windowed by `range`).

#### Parameters

| Name    | Type      | Description                                |
| ------- | --------- | ------------------------------------------ |
| `user`  | `address` | Wallet to inspect                          |
| `range` | `uint256` | Maximum CLOID window to scan (up to 1023). |

#### Return Values

| Name       | Type        | Description                             |
| ---------- | ----------- | --------------------------------------- |
| cloids     | `uint256[]` | Array of client order IDs found.        |
| userOrders | `Order[]`   | Decoded order data matching each CLOID. |

***

### getOrderByCloid

```solidity
function getOrderByCloid(uint256 userId, uint256 cloid) external view returns (Order)
```

Returns a single `Order` stored under composite CLOID for that user.

#### Parameters

| Name     | Type      | Description     |
| -------- | --------- | --------------- |
| `userId` | `uint256` | User identifier |
| `cloid`  | `uint256` | Client order ID |

#### Return Values

| Name    | Type    | Description                                        |
| ------- | ------- | -------------------------------------------------- |
| `order` | `Order` | Full order struct stored under that composite key. |

***

### getOrder

```solidity
function getOrder(address market, uint256 price, uint256 id) external view returns (Order)
```

Returns a specific `Order` by (market, price level, native id).

#### Parameters

| Name     | Type      | Description      |
| -------- | --------- | ---------------- |
| `market` | `address` | Market address   |
| `price`  | `uint256` | Order price      |
| `id`     | `uint256` | Order identifier |

#### Return Values

| Name    | Type    | Description    |
| ------- | ------- | -------------- |
| `order` | `Order` | Order details. |

***

### getPriceLevel

```solidity
function getPriceLevel(address market, uint256 price) external view returns (PriceLevel)
```

Returns `PriceLevel` aggregate for a specific price.

#### Parameters

| Name     | Type      | Description    |
| -------- | --------- | -------------- |
| `market` | `address` | Market address |
| `price`  | `uint256` | Order price    |

#### Return Values

| Name         | Type         | Description                                               |
| ------------ | ------------ | --------------------------------------------------------- |
| `priceLevel` | `PriceLevel` | Aggregate liquidity and internal pointers for that level. |

***

### getPriceLevels

```solidity
function getPriceLevels(address market, bool isAscending, uint256 startPrice, uint256 distance, uint256 interval, uint256 max) external returns (bytes)
```

Returns encoded order-book data for initialized price levels starting from a given price and direction.

#### Parameters

| Name          | Type      | Description                                                                            |
| ------------- | --------- | -------------------------------------------------------------------------------------- |
| `market`      | `address` | Market address                                                                         |
| `isAscending` | `bool`    | If true, search for price levels in the space above startPrice, otherwise search below |
| `startPrice`  | `uint256` | Start price, inclusive                                                                 |
| `distance`    | `uint256` | How many price increments to check                                                     |
| `interval`    | `uint256` | Step between prices                                                                    |
| `max`         | `uint256` | Maximum number of entries                                                              |

#### Return Values

| Name          | Type    | Description                                                                                                                              |
| ------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `priceLevels` | `bytes` | Byte string containing 32 byte chunks, with the first 16 bytes the price and last 16 bytes the sum of all order sizes at the price level |

***

### getPriceLevelsFromMid

```solidity
function getPriceLevelsFromMid(address market, uint256 distance, uint256 interval, uint256 max) external returns (uint256, uint256, bytes, bytes)
```

Returns the best bid and ask along with encoded order-book data for price levels around the mid-price.

#### Parameters

| Name       | Type      | Description                                 |
| ---------- | --------- | ------------------------------------------- |
| `market`   | `address` | Target market                               |
| `distance` | `uint256` | How many price increments to check each way |
| `interval` | `uint256` | Step size between ticks.                    |
| `max`      | `uint256` | Maximum number of entries                   |

#### Return Values

| Name         | Type      | Description                                                                    |
| ------------ | --------- | ------------------------------------------------------------------------------ |
| `highestBid` | `uint256` | The price of the highest buy order                                             |
| lowestAsk    | `uint256` | The price of the lowest sell order                                             |
| bids         | `bytes`   | Byte string representing all buy orders within distance of the bid-ask spread  |
| asks         | `bytes`   | Byte string representing all sell orders within distance of the bid-ask spread |

***

### getPrice

```solidity
function getPrice(address market) external returns (uint256, uint256, uint256)
```

Returns price, highestBid, lowestAsk given a market address.\
Delegated to market via `delegatecall`; non-view.

#### Parameters

| Name     | Type      | Description    |
| -------- | --------- | -------------- |
| `market` | `address` | Market address |

#### Return Values

| Name       | Type      | Description    |
| ---------- | --------- | -------------- |
| price      | `uint256` | Mid Price      |
| highestBid | `uint256` | Best bid price |
| lowestAsk  | `uint256` | Best ask price |

***

### getQuote

```solidity
function getQuote(address market, bool isBuy, bool isExactInput, bool isCompleteFill, uint256 size, uint256 worstPrice) external returns (uint256, uint256)
```

Simulates a trade to calculate the expected input and output amounts given trade direction, size, and worst acceptable price.

#### Parameters

| Name             | Type      | Description                                       |
| ---------------- | --------- | ------------------------------------------------- |
| `market`         | `address` | Market address                                    |
| `isBuy`          | `bool`    | True for buy orders, false for sell               |
| `isExactInput`   | `bool`    | True for exact input mode, false for exact output |
| `isCompleteFill` | `bool`    | Whether to require complete fill                  |
| `size`           | `uint256` | Order size                                        |
| `worstPrice`     | `uint256` | Worst acceptable execution price                  |

#### Return Values

| Name      | Type      | Description            |
| --------- | --------- | ---------------------- |
| amountIn  | `uint256` | Input tokens required  |
| amountOut | `uint256` | Output tokens required |

***

### deploy

```solidity
function deploy(bool isCanonical, address quoteAsset, address baseAsset, uint256 marketType, uint256 scaleFactor, uint256 tickSize, uint256 maxPrice, uint256 minSize, uint24 takerFee, uint24 makerRebate) external returns (address)
```

Deploys a new order-book market with the provided parameters; returns the market address.

#### Parameters

| Name          | Type      | Description                       |
| ------------- | --------- | --------------------------------- |
| `isCanonical` | `bool`    | Determines if market is canonical |
| `quoteAsset`  | `address` | Quote token address               |
| `baseAsset`   | `address` | Base token address                |
| `marketType`  | `uint256` | Market type identifier            |
| `scaleFactor` | `uint256` | Price scaling factor              |
| `tickSize`    | `uint256` | Minimum price increment           |
| `maxPrice`    | `uint256` | Maximum allowed price             |
| `minSize`     | `uint256` | Minimum order size                |
| `takerFee`    | `uint24`  | Taker fee in basis points         |
| `makerRebate` | `uint24`  | Maker rebate in basis points      |

#### Return Values

| Name   | Type      | Description                     |
| ------ | --------- | ------------------------------- |
| market | `address` | Newly deployed market contract. |

***

### registerUser

```solidity
function registerUser(address caller) external returns (uint256)
```

Registers a wallet to enable limit-order placement; this is automatically handled when routing through the main contract.

#### Parameters

| Name     | Type      | Description         |
| -------- | --------- | ------------------- |
| `caller` | `address` | Address of the user |

#### Return Values

| Name   | Type      | Description                             |
| ------ | --------- | --------------------------------------- |
| userId | `uint256` | Newly assigned numeric user identifier. |

***

### deposit

```solidity
function deposit(address token, uint256 amount) external payable returns (uint256)
```

Deposits ERC-20 or native (if `msg.value`) into protocol custody; returns credited amount (post-wrap/scale).

#### Parameters

| Name     | Type      | Description            |
| -------- | --------- | ---------------------- |
| `token`  | `address` | Token contract address |
| `amount` | `uint256` | Quantity to deposit    |

#### Return Values

| Name   | Type      | Description                                |
| ------ | --------- | ------------------------------------------ |
| userId | `uint256` | Depositing user’s ID (auto-created if new) |

***

### withdraw

```solidity
function withdraw(address to, address token, uint256 amount) external
```

Withdraws user custody balance to `to`

#### Parameters

| Name     | Type      | Description            |
| -------- | --------- | ---------------------- |
| `to`     | `address` | Recipient address      |
| `token`  | `address` | Token contract address |
| `amount` | `uint256` | Amount of tokens       |

***

### routerDeposit

```solidity
function routerDeposit(address token, uint256 amount) external payable
```

Router-privileged path to deposit on behalf of a user (supports `msg.value`).

#### Parameters

| Name     | Type      | Description            |
| -------- | --------- | ---------------------- |
| `token`  | `address` | Token contract address |
| `amount` | `uint256` | Deposit quantity       |

***

### routerWithdraw

```solidity
function routerWithdraw(address to, address token, uint256 amount) external
```

Router-privileged withdrawal on behalf of a user.

#### Parameters

| Name     | Type      | Description            |
| -------- | --------- | ---------------------- |
| `to`     | `address` | Recipient address      |
| `token`  | `address` | Token contract address |
| `amount` | `uint256` | Amount of tokens       |

***

### claimFees

```solidity
function claimFees(address to, address[] tokens) external returns (uint256[])
```

Claims accumulated maker rebates or referral fees owed to the caller.

#### Parameters

| Name     | Type        | Description              |
| -------- | ----------- | ------------------------ |
| `to`     | `address`   | Recipient address        |
| `tokens` | `address[]` | Array of token addresses |

#### Return Values

| Name    | Type        | Description               |
| ------- | ----------- | ------------------------- |
| amounts | `uint256[]` | Claimed amount per token. |

***

### queueClaimExpiredFees

```solidity
function queueClaimExpiredFees(address user, address[] tokens) external
```

Schedules recovery of expired, unclaimed fees for `user`.

#### Parameters

| Name     | Type        | Description              |
| -------- | ----------- | ------------------------ |
| `user`   | `address`   | Address of the user      |
| `tokens` | `address[]` | Array of token addresses |

***

### executeClaimExpiredFees

```solidity
function executeClaimExpiredFees(address user) external returns (uint256[])
```

Executes the queued expired-fee claim and returns recovered amounts.

#### Parameters

| Name   | Type      | Description         |
| ------ | --------- | ------------------- |
| `user` | `address` | Address of the user |

#### Return Values

| Name    | Type        | Description                               |
| ------- | ----------- | ----------------------------------------- |
| amounts | `uint256[]` | Amounts successfully recovered per token. |

***

### changeGov

```solidity
function changeGov(address newGov) external
```

*Updates configuration parameters.*

#### Parameters

| Name     | Type      | Description                          |
| -------- | --------- | ------------------------------------ |
| `newGov` | `address` | Address of new governance controller |

***

### changeFeeRecipient

```solidity
function changeFeeRecipient(address newFeeRecipient) external
```

*Updates configuration parameters.*

#### Parameters

| Name              | Type      | Description                          |
| ----------------- | --------- | ------------------------------------ |
| `newFeeRecipient` | `address` | New wallet to receive protocol fees. |

***

### changeFeeClaimDuration

```solidity
function changeFeeClaimDuration(uint256 newFeeClaimDuration) external
```

*Claims accumulated fees or rewards.*

#### Parameters

| Name                  | Type      | Description                                                    |
| --------------------- | --------- | -------------------------------------------------------------- |
| `newFeeClaimDuration` | `uint256` | New delay (seconds) between queue + execute expired-fee claim. |

***

### changeRefFeeStructure

```solidity
function changeRefFeeStructure(uint8 newFeeCommission, uint8 newFeeRebate) external
```

*Updates configuration parameters.*

#### Parameters

| Name               | Type    | Description                                |
| ------------------ | ------- | ------------------------------------------ |
| `newFeeCommission` | `uint8` | Proposed new referrer commission rate (%). |
| `newFeeRebate`     | `uint8` | Proposed maker rebate (%).                 |

***

### changeMarketParams

```solidity
function changeMarketParams(address market, uint256 newMinSize, uint24 newTakerFee, uint24 newMakerRebate, bool isAMMEnabled, bool isCanonical) external
```

*Updates configuration parameters.*

#### Parameters

| Name             | Type      | Description                        |
| ---------------- | --------- | ---------------------------------- |
| `market`         | `address` | Target market to update.           |
| `newMinSize`     | `uint256` | Updated minimum order size.        |
| `newTakerFee`    | `uint24`  | Updated taker fee (scaled bps).    |
| `newMakerRebate` | `uint24`  | Updated maker rebate (scaled bps). |
| `isAMMEnabled`   | `bool`    | Toggle AMM hybrid mode.            |
| `isCanonical`    | `bool`    | Toggle canonical-routing flag.     |

***

### changeMarketCreatorFee

```solidity
function changeMarketCreatorFee(address market, address newCreator, uint256 newCreatorFee) external
```

*Updates configuration parameters.*

#### Parameters

| Name            | Type      | Description              |
| --------------- | --------- | ------------------------ |
| `market`        | `address` | Market address           |
| `newCreator`    | `address` | Updated creator address. |
| `newCreatorFee` | `uint256` | Creator fee split        |

***

### changeLaunchpadParams

```solidity
function changeLaunchpadParams(LaunchpadParams newLaunchpadParams) external
```

*Updates configuration parameters.*

#### Parameters

| Name                 | Type              | Description                                          |
| -------------------- | ----------------- | ---------------------------------------------------- |
| `newLaunchpadParams` | `LaunchpadParams` | Struct containing updated launchpad global settings. |

***

### addCanonicalDeployer

```solidity
function addCanonicalDeployer(address deployer) external
```

*Grant canonical-deployer status.*

#### Parameters

| Name       | Type      | Description       |
| ---------- | --------- | ----------------- |
| `deployer` | `address` | Address parameter |

***

### removeCanonicalDeployer

```solidity
function removeCanonicalDeployer(address deployer) external
```

*Revoke canonical-deployer status.*

#### Parameters

| Name       | Type      | Description       |
| ---------- | --------- | ----------------- |
| `deployer` | `address` | Address parameter |

***

### approveForwarder

```solidity
function approveForwarder(address forwarder) external
```

*Approves an address to place and cancel orders on a user's behalf. This is equivalent to giving the forwarder full control of your account including the ability to spend your tokens to their sole discretion, therefore this method should be used with extreme caution.*

#### Parameters

| Name        | Type      | Description                                                            |
| ----------- | --------- | ---------------------------------------------------------------------- |
| `forwarder` | `address` | Contract or EOA allowed to place and cancel orders on caller’s behalf. |

***

### removeForwarder

```solidity
function removeForwarder(address forwarder) external
```

*Removes an address from authorization.*

#### Parameters

| Name        | Type      | Description       |
| ----------- | --------- | ----------------- |
| `forwarder` | `address` | Address parameter |

***

### clearCloidSlots

```solidity
function clearCloidSlots(uint256 userId, uint256[] ids) external
```

*Clears stored data.*

#### Parameters

| Name     | Type        | Description                      |
| -------- | ----------- | -------------------------------- |
| `userId` | `uint256`   | User whose order slots to clear. |
| `ids`    | `uint256[]` | CLOID identifiers being reset.   |

***

### getReserves

```solidity
function getReserves(address market) external returns (uint112, uint112)
```

*Returns current reserve balances.*

#### Parameters

| Name     | Type      | Description    |
| -------- | --------- | -------------- |
| `market` | `address` | Market address |

#### Return Values

| Name         | Type      | Description                  |
| ------------ | --------- | ---------------------------- |
| reserveQuote | `uint112` | Current quote-token reserve. |
| reserveBase  | `uint112` | Current base-token reserve.  |

***

### addLiquidity

```solidity
function addLiquidity(address market, address to, uint256 amountQuoteDesired, uint256 amountBaseDesired, uint256 amountQuoteMin, uint256 amountBaseMin) external payable returns (uint256)
```

*Adds liquidity to a market.*

#### Parameters

| Name                 | Type      | Description                            |
| -------------------- | --------- | -------------------------------------- |
| `market`             | `address` | Market address to supply liquidity to. |
| `to`                 | `address` | Recipient address of LP position.      |
| `amountQuoteDesired` | `uint256` | Intended quote deposit.                |
| `amountBaseDesired`  | `uint256` | Intended base deposit.                 |
| `amountQuoteMin`     | `uint256` | Minimum acceptable quote.              |
| `amountBaseMin`      | `uint256` | Minimum acceptable base.               |

#### Return Values

| Name        | Type      | Description              |
| ----------- | --------- | ------------------------ |
| `liquidity` | `uint256` | Minted liquidity amount. |

***

### removeLiquidity

```solidity
function removeLiquidity(address market, address to, uint256 liquidity, uint256 amountQuoteMin, uint256 amountBaseMin) external returns (uint256, uint256)
```

*Removes liquidity from a market.*

#### Parameters

| Name             | Type      | Description                |
| ---------------- | --------- | -------------------------- |
| `market`         | `address` | Market address             |
| `to`             | `address` | Recipient address          |
| `liquidity`      | `uint256` | LP tokens to burn.         |
| `amountQuoteMin` | `uint256` | Minimum quote token amount |
| `amountBaseMin`  | `uint256` | Minimum base token amount  |

#### Return Values

| Name        | Type      | Description            |
| ----------- | --------- | ---------------------- |
| amountQuote | `uint256` | Quote tokens returned. |
| amountBase  | `uint256` | Base tokens returned.  |

***

### removeLiquidityETH

```solidity
function removeLiquidityETH(address market, address to, uint256 liquidity, uint256 amountQuoteMin, uint256 amountBaseMin) external returns (uint256 amountQuote, uint256 amountBase)
```

*Removes liquidity from a market.*

#### Parameters

| Name             | Type      | Description                |
| ---------------- | --------- | -------------------------- |
| `market`         | `address` | Market address             |
| `to`             | `address` | Recipient address          |
| `liquidity`      | `uint256` | Liquidity amount           |
| `amountQuoteMin` | `uint256` | Minimum quote token amount |
| `amountBaseMin`  | `uint256` | Minimum base token amount  |

#### Return Values

| Name          | Type      | Description        |
| ------------- | --------- | ------------------ |
| `amountQuote` | `uint256` | Quote token amount |
| `amountBase`  | `uint256` | Base token amount  |

***

### marketOrder

```solidity
function marketOrder(address market, bool isBuy, bool isExactInput, uint256 options, uint256 orderType, uint256 size, uint256 worstPrice, address referrer, address user) external returns (uint256, uint256, uint256)
```

*Executes a market order.*

#### Parameters

| Name           | Type      | Description                                  |
| -------------- | --------- | -------------------------------------------- |
| `market`       | `address` | Market address                               |
| `isBuy`        | `bool`    | <p>True = buy<br>False = sell.</p>           |
| `isExactInput` | `bool`    | Indicates whether `size` is input or output. |
| `options`      | `uint256` | Bit-flags for ETH handling and mode          |
| `orderType`    | `uint256` | Internal order execution type.               |
| `size`         | `uint256` | Trade amount.                                |
| `worstPrice`   | `uint256` | Maximum slippage or price limit.             |
| `referrer`     | `address` | Optional referral address.                   |
| `user`         | `address` | Account placing the order                    |

#### Return Values

| Name      | Type      | Description                           |
| --------- | --------- | ------------------------------------- |
| amountIn  | `uint256` | Tokens spent                          |
| amountOut | `uint256` | Tokens received                       |
| id        | `uint256` | Residual order ID if partially filled |

***

### limitOrder

```solidity
function limitOrder(address market, bool isBuy, uint256 options, uint256 price, uint256 size, address user) external returns (uint256)
```

*Places a limit order.*

#### Parameters

| Name      | Type      | Description                        |
| --------- | --------- | ---------------------------------- |
| `market`  | `address` | Market address                     |
| `isBuy`   | `bool`    | <p>True = buy<br>False = sell.</p> |
| `options` | `uint256` | Execution flags.                   |
| `price`   | `uint256` | Limit price.                       |
| `size`    | `uint256` | Order size                         |
| `user`    | `address` | Address of the user                |

#### Return Values

| Name | Type      | Description       |
| ---- | --------- | ----------------- |
| `id` | `uint256` | Created order ID. |

***

### cancelOrder

```solidity
function cancelOrder(address market, uint256 options, uint256 price, uint256 id, address user) external returns (uint256)
```

*Cancels an existing order.*&#x20;

#### Parameters

| Name      | Type      | Description         |
| --------- | --------- | ------------------- |
| `market`  | `address` | Market address      |
| `options` | `uint256` | Execution flags     |
| `price`   | `uint256` | Price level         |
| `id`      | `uint256` | Order ID            |
| `user`    | `address` | Address of the user |

#### Return Values

| Name   | Type      | Description                   |
| ------ | --------- | ----------------------------- |
| `size` | `uint256` | Amount canceled and released. |

***

### replaceOrder

```solidity
function replaceOrder(address market, uint256 options, uint256 price, uint256 id, uint256 newPrice, uint256 size, address referrer, address user) external returns (uint256)
```

*Places a limit order.*

#### Parameters

| Name       | Type      | Description                      |
| ---------- | --------- | -------------------------------- |
| `market`   | `address` | Market address                   |
| `options`  | `uint256` | Flags for mode                   |
| `price`    | `uint256` | Old price level                  |
| `id`       | `uint256` | Order ID                         |
| `newPrice` | `uint256` | New price level                  |
| `size`     | `uint256` | New Order size                   |
| `referrer` | `address` | Referrer address for fee sharing |
| `user`     | `address` | Address of the user              |

#### Return Values

| Name | Type      | Description              |
| ---- | --------- | ------------------------ |
| id   | `uint256` | New or current order ID. |

***

### batchOrders

```solidity
function batchOrders(address market, Action[] actions, uint256 options, uint256 deadline, address referrer, address user) external payable
```

*Executes multiple limit or market order in a single transaction.*

#### Parameters

| Name       | Type       | Description                      |
| ---------- | ---------- | -------------------------------- |
| `market`   | `address`  | Market address                   |
| `actions`  | `Action[]` | Array of actions to execute      |
| `options`  | `uint256`  | Bitfield of execution options    |
| `deadline` | `uint256`  | Transaction deadline timestamp   |
| `referrer` | `address`  | Referrer address for fee sharing |
| `user`     | `address`  | Address of the user              |

***

### getAmountsOut

```solidity
function getAmountsOut(uint256 amountIn, address[] path) external returns (uint256[])
```

*Calculates token amounts for routing. (*`eth` sentinel auto-mapped to WETH at each hop; reverts on unresolved market or placeholder)

#### Parameters

| Name       | Type        | Description        |
| ---------- | ----------- | ------------------ |
| `amountIn` | `uint256`   | Input token amount |
| `path`     | `address[]` | Token swap path    |

#### Return Values

| Name      | Type        | Description                                          |
| --------- | ----------- | ---------------------------------------------------- |
| `amounts` | `uint256[]` | Expect Output per hop, final element is total output |

***

### getAmountsIn

```solidity
function getAmountsIn(uint256 amountOut, address[] path) external returns (uint256[])
```

*Calculates token amounts for routing. (*`eth` sentinel auto-mapped to WETH at each hop; reverts on unresolved market or placeholder)

#### Parameters

| Name        | Type        | Description         |
| ----------- | ----------- | ------------------- |
| `amountOut` | `uint256`   | Output token amount |
| `path`      | `address[]` | Token swap path     |

#### Return Values

| Name      | Type        | Description                                          |
| --------- | ----------- | ---------------------------------------------------- |
| `amounts` | `uint256[]` | Required input per hop, final element is total input |

***

### swapExactETHForTokens

```solidity
function swapExactETHForTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline, address referrer) external payable returns (uint256[])
```

*Swaps tokens via routing.*

#### Parameters

| Name           | Type        | Description                      |
| -------------- | ----------- | -------------------------------- |
| `amountOutMin` | `uint256`   | Minimum acceptable output amount |
| `path`         | `address[]` | Token swap path                  |
| `to`           | `address`   | Recipient address                |
| `deadline`     | `uint256`   | Transaction deadline timestamp   |
| `referrer`     | `address`   | Referrer address for fee sharing |

#### Return Values

| Name    | Type        | Description    |
| ------- | ----------- | -------------- |
| amounts | `uint256[]` | Numeric result |

***

### swapExactTokensForETH

```solidity
function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline, address referrer) external returns (uint256[])
```

*Swaps tokens via routing.*

#### Parameters

| Name           | Type        | Description                      |
| -------------- | ----------- | -------------------------------- |
| `amountIn`     | `uint256`   | Input token amount               |
| `amountOutMin` | `uint256`   | Minimum acceptable output amount |
| `path`         | `address[]` | Token swap path                  |
| `to`           | `address`   | Recipient address                |
| `deadline`     | `uint256`   | Transaction deadline timestamp   |
| `referrer`     | `address`   | Referrer address for fee sharing |

#### Return Values

| Name | Type        | Description    |
| ---- | ----------- | -------------- |
|      | `uint256[]` | Numeric result |

***

### swapExactTokensForTokens

```solidity
function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline, address referrer) external returns (uint256[])
```

*Swaps tokens via routing.*

#### Parameters

| Name           | Type        | Description                      |
| -------------- | ----------- | -------------------------------- |
| `amountIn`     | `uint256`   | Input token amount               |
| `amountOutMin` | `uint256`   | Minimum acceptable output amount |
| `path`         | `address[]` | Token swap path                  |
| `to`           | `address`   | Recipient address                |
| `deadline`     | `uint256`   | Transaction deadline timestamp   |
| `referrer`     | `address`   | Referrer address for fee sharing |

#### Return Values

| Name | Type        | Description    |
| ---- | ----------- | -------------- |
|      | `uint256[]` | Numeric result |

***

### swapETHForExactTokens

```solidity
function swapETHForExactTokens(uint256 amountOut, address[] path, address to, uint256 deadline, address referrer) external payable returns (uint256[])
```

*Swaps tokens via routing.*

#### Parameters

| Name        | Type        | Description                      |
| ----------- | ----------- | -------------------------------- |
| `amountOut` | `uint256`   | Output token amount              |
| `path`      | `address[]` | Token swap path                  |
| `to`        | `address`   | Recipient address                |
| `deadline`  | `uint256`   | Transaction deadline timestamp   |
| `referrer`  | `address`   | Referrer address for fee sharing |

#### Return Values

| Name | Type        | Description    |
| ---- | ----------- | -------------- |
|      | `uint256[]` | Numeric result |

***

### swapTokensForExactETH

```solidity
function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline, address referrer) external returns (uint256[])
```

*Swaps tokens via routing.*

#### Parameters

| Name          | Type        | Description                         |
| ------------- | ----------- | ----------------------------------- |
| `amountOut`   | `uint256`   | Output token amount                 |
| `amountInMax` | `uint256`   | Maximum input amount willing to pay |
| `path`        | `address[]` | Token swap path                     |
| `to`          | `address`   | Recipient address                   |
| `deadline`    | `uint256`   | Transaction deadline timestamp      |
| `referrer`    | `address`   | Referrer address for fee sharing    |

#### Return Values

| Name | Type        | Description    |
| ---- | ----------- | -------------- |
|      | `uint256[]` | Numeric result |

***

### swapTokensForExactTokens

```solidity
function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline, address referrer) external returns (uint256[])
```

*Swaps tokens via routing.*

#### Parameters

| Name          | Type        | Description                         |
| ------------- | ----------- | ----------------------------------- |
| `amountOut`   | `uint256`   | Output token amount                 |
| `amountInMax` | `uint256`   | Maximum input amount willing to pay |
| `path`        | `address[]` | Token swap path                     |
| `to`          | `address`   | Recipient address                   |
| `deadline`    | `uint256`   | Transaction deadline timestamp      |
| `referrer`    | `address`   | Referrer address for fee sharing    |

#### Return Values

| Name | Type        | Description    |
| ---- | ----------- | -------------- |
|      | `uint256[]` | Numeric result |

***

### swap

```solidity
function swap(bool exactInput, address tokenIn, address tokenOut, uint256 orderType, uint256 size, uint256 worstPrice, uint256 deadline, address referrer) external payable returns (uint256, uint256, uint256)
```

*Swaps tokens via a single market with the option for advanced order types (Partial fill, MTL).*

#### Parameters

| Name         | Type      | Description                      |
| ------------ | --------- | -------------------------------- |
| `exactInput` | `bool`    | Boolean flag                     |
| `tokenIn`    | `address` | Input token address              |
| `tokenOut`   | `address` | Output token address             |
| `orderType`  | `uint256` | Type of order                    |
| `size`       | `uint256` | Order size                       |
| `worstPrice` | `uint256` | Worst acceptable execution price |
| `deadline`   | `uint256` | Transaction deadline timestamp   |
| `referrer`   | `address` | Referrer address for fee sharing |

#### Return Values

| Name         | Type      | Description    |
| ------------ | --------- | -------------- |
| userId       | `uint256` | Numeric result |
| balanceOrOut | `uint256` | Numeric result |
| id           | `uint256` | Numeric result |

***

### placeLimitOrder

```solidity
function placeLimitOrder(address tokenIn, address tokenOut, uint256 price, uint256 size, uint256 deadline) external payable returns (uint256)
```

*Places a limit order.*

#### Parameters

| Name       | Type      | Description          |
| ---------- | --------- | -------------------- |
| `tokenIn`  | `address` | Input token address  |
| `tokenOut` | `address` | Output token address |
| `price`    | `uint256` | Order price          |
| `size`     | `uint256` | Order size           |
| `deadline` | `uint256` | Expiry               |

#### Return Values

| Name | Type      | Description              |
| ---- | --------- | ------------------------ |
| `id` | `uint256` | Created order identifier |

***

### cancelLimitOrder

```solidity
function cancelLimitOrder(address tokenIn, address tokenOut, uint256 price, uint256 id, uint256 deadline) external returns (uint256)
```

*Cancels an existing order.*

#### Parameters

| Name       | Type      | Description          |
| ---------- | --------- | -------------------- |
| `tokenIn`  | `address` | Input token address  |
| `tokenOut` | `address` | Output token address |
| `price`    | `uint256` | Order price          |
| `id`       | `uint256` | Order identifier     |
| `deadline` | `uint256` | Expiry               |

#### Return Values

| Name   | Type      | Description |
| ------ | --------- | ----------- |
| `size` | `uint256` | Order size  |

***

### replaceLimitOrder

```solidity
function replaceLimitOrder(bool isPostOnly, bool isDecrease, address tokenIn, address tokenOut, uint256 price, uint256 id, uint256 newPrice, uint256 newSize, uint256 deadline, address referrer) external payable returns (uint256)
```

*Replaces a limit order.*

#### Parameters

| Name         | Type      | Description                     |
| ------------ | --------- | ------------------------------- |
| `isPostOnly` | `bool`    | Prevent immediate fills if true |
| `isDecrease` | `bool`    | True if reducing size           |
| `tokenIn`    | `address` | Input token address             |
| `tokenOut`   | `address` | Output token address            |
| `price`      | `uint256` | Order price                     |
| `id`         | `uint256` | Order ID                        |
| `newPrice`   | `uint256` | New order price                 |
| `newSize`    | `uint256` | New order size                  |
| `deadline`   | `uint256` | Expiry                          |
| `referrer`   | `address` | Referrer address                |

#### Return Values

| Name | Type      | Description          |
| ---- | --------- | -------------------- |
| `id` | `uint256` | New/Current Order ID |

***

### multiBatchOrders

```solidity
function multiBatchOrders(Batch[] batches, uint256 deadline, address referrer) external payable
```

Executes cross-market batches atomically. *(*&#x45;TH handling: “Wraps ETH to WETH for in-call usage; refunds residual WETH as ETH at end.)

#### Parameters

| Name       | Type      | Description                      |
| ---------- | --------- | -------------------------------- |
| `batches`  | `Batch[]` | Array of batches to execute      |
| `deadline` | `uint256` | Transaction deadline timestamp   |
| `referrer` | `address` | Referrer address for fee sharing |

***

### createToken

```solidity
function createToken(string name, string symbol, string metadataCID, string description, string social1, string social2, string social3, string social4) external payable returns (address token)
```

*Creates a new launchpad token with the option for an initial buy.*

#### Parameters

| Name          | Type     | Description       |
| ------------- | -------- | ----------------- |
| `name`        | `string` | Token name        |
| `symbol`      | `string` | Token symbol      |
| `metadataCID` | `string` | IPFS metadata CID |
| `description` | `string` | Text description  |
| `social1`     | `string` | Social media link |
| `social2`     | `string` | Social media link |
| `social3`     | `string` | Social media link |
| `social4`     | `string` | Social media link |

#### Return Values

| Name    | Type      | Description            |
| ------- | --------- | ---------------------- |
| `token` | `address` | Deployed token address |

***

### buy

```solidity
function buy(bool isExactInput, address token, uint256 amountIn, uint256 amountOut) external payable returns (uint256, uint256, bool)
```

*Buys tokens on the launchpad.*

#### Parameters

| Name           | Type      | Description                                       |
| -------------- | --------- | ------------------------------------------------- |
| `isExactInput` | `bool`    | True for exact input mode, false for exact output |
| `token`        | `address` | Token contract address                            |
| `amountIn`     | `uint256` | Input token amount                                |
| `amountOut`    | `uint256` | Output token amount                               |

#### Return Values

| Name           | Type      | Description                  |
| -------------- | --------- | ---------------------------- |
| `inputAmount`  | `uint256` | ETH spent                    |
| `outputAmount` | `uint256` | Tokens received              |
| `graduated`    | `bool`    | True = market auto-graduated |

***

### sell

```solidity
function sell(bool isExactInput, address token, uint256 amountIn, uint256 amountOut) external returns (uint256, uint256)
```

*Sells tokens on the launchpad.*

#### Parameters

| Name           | Type      | Description                                       |
| -------------- | --------- | ------------------------------------------------- |
| `isExactInput` | `bool`    | True for exact input mode, false for exact output |
| `token`        | `address` | Launchpad token                                   |
| `amountIn`     | `uint256` | Tokens sold                                       |
| `amountOut`    | `uint256` | Expected WETH/ETH output                          |

#### Return Values

| Name           | Type      | Description  |
| -------------- | --------- | ------------ |
| `inputAmount`  | `uint256` | Tokens sold  |
| `outputAmount` | `uint256` | ETH received |

***

### getVirtualReserves

```solidity
function getVirtualReserves(address token) external view returns (uint256, uint256)
```

*Returns current launchpad bonding curve reserve balances. Empty return values indicate a token has already graduated.*

#### Parameters

| Name    | Type      | Description             |
| ------- | --------- | ----------------------- |
| `token` | `address` | Launchpad token address |

#### Return Values

| Name                 | Type      | Description                    |
| -------------------- | --------- | ------------------------------ |
| virtualNativeReserve | `uint256` | Virtual native-side liquidity. |
| virtualTokenReserve  | `uint256` | Virtual token-side liquidity.  |

***

## Fallback

The fallback function is gas-optimized and intended for use by market makers and other high frequency automated trading strategies. Calldata is in 32-byte chunks, with each chunk either representing a batch header or action. By default, msg.sender is used in place of all address parameters for each action.

### Top-Level Layout

`Crystal.sol` fallback calldata is a sequence of market batches:

```
calldata = batch0 || batch1 || batch2 || ...
```

Each batch is:

```
batch = batchHeader || action0 || action1 || ... || actionN
```

There is no function selector.

### Batch Header

Each batch starts with one 32-byte word.

| Bits       | Field         | Type      | Notes                                          |
| ---------- | ------------- | --------- | ---------------------------------------------- |
| `0..159`   | `market`      | `address` | target market                                  |
| `160..171` | `actionCount` | `uint12`  | number of 32-byte action words that follow     |
| `172..251` | `bid`         | `uint80`  | optional priority bid sent to `block.coinbase` |
| `252..255` | `balanceMode` | `uint4`   | currently expected to be `0` or `1`            |

#### Batch Header Formula

```
batchHeader =
    uint160(market)
    | (actionCount << 160)
    | (bid << 172)
    | (balanceMode << 252)
```

#### Balance Modes

* `0`: external settlement
* `1`: internal settlement

When `Crystal.sol` delegates into `CrystalMarket.sol`, it automatically rebuilds the inner header as:

```
marketHeader = userId | (balanceMode << 44)
```

So when calling `Crystal.sol` fallback, you do not encode `userId` yourself in calldata. `Crystal.sol` loads the caller's `userId` from storage and injects it.

### Action Word

Each action is still one 32-byte word.

| Bits       | Field              | Type      | Notes                              |
| ---------- | ------------------ | --------- | ---------------------------------- |
| `0..111`   | `param2`           | `uint112` | meaning depends on action          |
| `112..191` | `param1`           | `uint80`  | meaning depends on action          |
| `192..201` | `cloid`            | `uint10`  | client order id                    |
| `202..247` | unused             | -         | set to `0`                         |
| `248`      | `isRequireSuccess` | `uint1`   | `1` reverts whole batch on failure |
| `249..251` | unused             | -         | set to `0`                         |
| `252..255` | `action`           | `uint4`   | action code                        |

#### Generic Action Formula

```
word =
    param2
    | (param1 << 112)
    | (cloid << 192)
    | (isRequireSuccess << 248)
    | (action << 252)
```

### Action Codes

| Code | Meaning                 |
| ---- | ----------------------- |
| `1`  | cancel order            |
| `2`  | limit buy               |
| `3`  | limit sell              |
| `4`  | market-to-limit buy     |
| `5`  | market-to-limit sell    |
| `6`  | partial buy             |
| `7`  | partial sell            |
| `8`  | partial buy, gas-aware  |
| `9`  | partial sell, gas-aware |
| `10` | complete buy            |
| `11` | complete sell           |
| `12` | decrease order          |

### Per-Action Encoding

#### `1` Cancel Order

Cancel by native order id:

| Field    | Value   |
| -------- | ------- |
| `param1` | `price` |
| `param2` | `id`    |
| `cloid`  | `0`     |

Cancel by cloid:

| Field    | Value           |
| -------- | --------------- |
| `param1` | `0`             |
| `param2` | `0`             |
| `cloid`  | client order id |

#### `2` Limit Buy

| Field    | Value                    |
| -------- | ------------------------ |
| `param1` | `price`                  |
| `param2` | `size`                   |
| `cloid`  | optional client order id |

#### `3` Limit Sell

| Field    | Value                    |
| -------- | ------------------------ |
| `param1` | `price`                  |
| `param2` | `size`                   |
| `cloid`  | optional client order id |

#### `4` to `11` Market-Style Orders

| Field    | Value                    |
| -------- | ------------------------ |
| `param1` | `worstPrice`             |
| `param2` | `size`                   |
| `cloid`  | optional client order id |

Meanings:

| Code | Meaning                 |
| ---- | ----------------------- |
| `4`  | market-to-limit buy     |
| `5`  | market-to-limit sell    |
| `6`  | partial buy             |
| `7`  | partial sell            |
| `8`  | partial buy, gas-aware  |
| `9`  | partial sell, gas-aware |
| `10` | complete buy            |
| `11` | complete sell           |

#### `12` Decrease Order

Decrease by native order id:

| Field           | Value                        |
| --------------- | ---------------------------- |
| `param1`        | `price`                      |
| bits `192..232` | native order `id` (`uint41`) |
| `param2`        | `decreaseAmount`             |

Decrease by cloid:

| Field           | Value            |
| --------------- | ---------------- |
| `param1`        | `0`              |
| bits `192..201` | `cloid`          |
| `param2`        | `decreaseAmount` |

### Limits

| Field             | Size      |
| ----------------- | --------- |
| `actionCount`     | `uint12`  |
| `bid`             | `uint80`  |
| `cloid`           | `uint10`  |
| `param1`          | `uint80`  |
| `param2`          | `uint112` |
| native order `id` | `uint41`  |

All unused bits should be zeroed.

***

## Events

### MarketCreated

```solidity
event MarketCreated(indexed bool isCanonical, indexed address quoteAsset, indexed address baseAsset, address market, ICrystal.TokenMetadata quoteInfo, ICrystal.TokenMetadata baseInfo, ICrystal.MarketDetails marketInfo);
```

Deployed new market with its assets and setup details.

#### Parameters

| Name          | Type                     | Description                        |
| ------------- | ------------------------ | ---------------------------------- |
| `isCanonical` | `indexed bool`           | Determines if market is canonical. |
| `quoteAsset`  | `indexed address`        | Quote token address                |
| `baseAsset`   | `indexed address`        | Base token address                 |
| `market`      | `address`                | Market address                     |
| `quoteInfo`   | `ICrystal.TokenMetadata` | Parameter value                    |
| `baseInfo`    | `ICrystal.TokenMetadata` | Parameter value                    |
| `marketInfo`  | `ICrystal.MarketDetails` | Parameter value                    |

***

### MarketParamsChanged

```solidity
event MarketParamsChanged(indexed address market, uint256 minSize, uint24 takerFee, uint24 makerRebate, bool isAMMEnabled);
```

A market’s key settings (like fees or minimum size) were updated.

#### Parameters

| Name           | Type              | Description                    |
| -------------- | ----------------- | ------------------------------ |
| `market`       | `indexed address` | Market address                 |
| `minSize`      | `uint256`         | Minimum order size             |
| `takerFee`     | `uint24`          | Taker fee in basis points      |
| `makerRebate`  | `uint24`          | Maker rebate in basis points   |
| `isAMMEnabled` | `bool`            | True = AMM backstop is enabled |

***

### GovChanged

```solidity
event GovChanged(address prev, address gov);
```

Protocol governance address changed.

#### Parameters

| Name   | Type      | Description      |
| ------ | --------- | ---------------- |
| `prev` | `address` | Prev gov address |
| `gov`  | `address` | New gov address  |

***

### UserRegistered

```solidity
event UserRegistered(indexed bool isMargin, indexed address user, indexed uint256 userId);
```

*Emitted when a new user is registered.*

#### Parameters

| Name       | Type              | Description                                |
| ---------- | ----------------- | ------------------------------------------ |
| `isMargin` | `indexed bool`    | Account Type, right now its false for spot |
| `user`     | `indexed address` | REgistered wallet address                  |
| `userId`   | `indexed uint256` | User identifier                            |

***

### Deposit

```solidity
event Deposit(indexed address user, indexed uint256 userId, indexed address token, uint256 amount);
```

*Emitted when user* deposits a token into protocol custody.

#### Parameters

| Name     | Type              | Description         |
| -------- | ----------------- | ------------------- |
| `user`   | `indexed address` | Depositor's address |
| `userId` | `indexed uint256` | Depositor's user ID |
| `token`  | `indexed address` | Token deposited     |
| `amount` | `uint256`         | Amount of tokens    |

***

### Withdraw

```solidity
event Withdraw(indexed address user, indexed uint256 userId, indexed address token, uint256 amount);
```

*Emitted when user* deposits a token from protocol custody.

#### Parameters

| Name     | Type              | Description            |
| -------- | ----------------- | ---------------------- |
| `user`   | `indexed address` | Recipient wallet       |
| `userId` | `indexed uint256` | Recipient's user ID    |
| `token`  | `indexed address` | Token contract address |
| `amount` | `uint256`         | Amount sent out        |

***

### RewardsClaimed

```solidity
event RewardsClaimed(indexed address user, address[] tokens, uint256[] amounts);
```

*Emitted when rewards or fees are claimed.*

#### Parameters

| Name      | Type              | Description         |
| --------- | ----------------- | ------------------- |
| `user`    | `indexed address` | Address of the user |
| `tokens`  | `address[]`       | Tokens claimed      |
| `amounts` | `uint256[]`       | Amounts per token   |

***

### Trade

```solidity
event Trade(indexed address market, indexed address user, bool isBuy, uint256 amountIn, uint256 amountOut, uint256 startPrice, uint256 endPrice);
```

*Emitted when a trade is executed.*

#### Parameters

| Name         | Type              | Description                |
| ------------ | ----------------- | -------------------------- |
| `market`     | `indexed address` | Market address             |
| `user`       | `indexed address` | Trader wallet              |
| `isBuy`      | `bool`            | True if buy, false if sell |
| `amountIn`   | `uint256`         | Spent amount               |
| `amountOut`  | `uint256`         | Received amount            |
| `startPrice` | `uint256`         | Price when order is placed |
| `endPrice`   | `uint256`         | Price when order is filled |

***

### OrdersUpdated

```solidity
event OrdersUpdated(indexed address market, indexed address user, bytes orderData);
```

Represents a limit order’s key data — price, size, order type, user ID, and partial-fill progress indicators.

#### Parameters

| Name        | Type              | Description                                      |
| ----------- | ----------------- | ------------------------------------------------ |
| `market`    | `indexed address` | Market address                                   |
| `user`      | `indexed address` | Order owner address                              |
| `orderData` | `bytes`           | Compact batch of placed/changed/canceled orders. |

***

### Fill

```solidity
event Fill(indexed address market, indexed address user, uint256 fillInfo, uint256 fillAmount);
```

*Emitted when an order is filled.*

#### Parameters

| Name         | Type              | Description                                                                                                                                               |
| ------------ | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `market`     | `indexed address` | Market address                                                                                                                                            |
| `user`       | `indexed address` | Order owner address                                                                                                                                       |
| `fillInfo`   | `uint256`         | Bit 255 is set to 1 if the aggressing fill is a sell order, 0 if buy. Bits 168-248 is the price, 112-168 is the order id, and 0-112 is the remaining size |
| `fillAmount` | `uint256`         | Size of fill                                                                                                                                              |

***

### TokenCreated

```solidity
event TokenCreated(indexed address token, indexed address creator, string name, string symbol, string metadataCID, string description, string social1, string social2, string social3, string social4);
```

*Emitted when a new entity is created.*

#### Parameters

| Name          | Type              | Description            |
| ------------- | ----------------- | ---------------------- |
| `token`       | `indexed address` | Token contract address |
| `creator`     | `indexed address` | Token creator address  |
| `name`        | `string`          | Token name             |
| `symbol`      | `string`          | Token symbol           |
| `metadataCID` | `string`          | IPFS metadata CID      |
| `description` | `string`          | Description text       |
| `social1`     | `string`          | Social media link      |
| `social2`     | `string`          | Social media link      |
| `social3`     | `string`          | Social media link      |
| `social4`     | `string`          | Social media link      |

***

### Migrated

```solidity
event Migrated(indexed address token);
```

*Emitted when migration occurs* (e.g., to market)

#### Parameters

| Name    | Type              | Description            |
| ------- | ----------------- | ---------------------- |
| `token` | `indexed address` | Token contract address |

***

### LaunchpadTrade

```solidity
event LaunchpadTrade(indexed address token, indexed address user, bool isBuy, uint256 amountIn, uint256 amountOut, uint256 virtualNativeReserve, uint256 virtualTokenReserve);
```

Launchpad swap executed with updated virtual reserves.

#### Parameters

| Name                   | Type              | Description                         |
| ---------------------- | ----------------- | ----------------------------------- |
| `token`                | `indexed address` | Token contract address              |
| `user`                 | `indexed address` | Address of the user                 |
| `isBuy`                | `bool`            | True for buy orders, false for sell |
| `amountIn`             | `uint256`         | Input token amount                  |
| `amountOut`            | `uint256`         | Output token amount                 |
| `virtualNativeReserve` | `uint256`         | Post-swap native token reserve      |
| `virtualTokenReserve`  | `uint256`         | Post-swap launchpad token reserve   |

***

### Mint

```solidity
event Mint(indexed address market, indexed address sender, uint amountQuote, uint amountBase);
```

*Emitted when liquidity is* added to a market pair with actual amounts.

#### Parameters

| Name          | Type              | Description        |
| ------------- | ----------------- | ------------------ |
| `market`      | `indexed address` | Market address     |
| `sender`      | `indexed address` | Address parameter  |
| `amountQuote` | `uint`            | Quote token amount |
| `amountBase`  | `uint`            | Base token amount  |

***

### Burn

```solidity
event Burn(indexed address market, indexed address sender, uint amountQuote, uint amountBase, indexed address to);
```

Liquidity removed from a market pair with actual amounts and recipient.

#### Parameters

| Name          | Type              | Description        |
| ------------- | ----------------- | ------------------ |
| `market`      | `indexed address` | Market address     |
| `sender`      | `indexed address` | Address parameter  |
| `amountQuote` | `uint`            | Quote token amount |
| `amountBase`  | `uint`            | Base token amount  |
| `to`          | `indexed address` | Recipient address  |

***

### Sync

```solidity
event Sync(indexed address market, uint112 reserve0, uint112 reserve1);
```

*Emitted when reserves are synchronized.*

#### Parameters

| Name       | Type              | Description    |
| ---------- | ----------------- | -------------- |
| `market`   | `indexed address` | Market address |
| `reserve0` | `uint112`         | Numeric value  |
| `reserve1` | `uint112`         | Numeric value  |

***

## Structs

### InternalOrder

```solidity
struct InternalOrder {
    uint256 size;
    uint256 orderType;
    uint256 userId;
    uint256 fillBefore;
    uint256 fillAfter;
}
```

Compact internal storage format for an order, tracking size, type, user, and partial-fill progress.

#### Parameters

| Name         | Type      | Description           |
| ------------ | --------- | --------------------- |
| `size`       | `uint256` | Order size            |
| `orderType`  | `uint256` | Type of order         |
| `userId`     | `uint256` | User identifier       |
| `fillBefore` | `uint256` | Fill before timestamp |
| `fillAfter`  | `uint256` | Fill after timestamp  |

***

### Order

```solidity
struct Order {
    bool isBuy;
    address market;
    uint256 price;
    uint256 size;
    uint256 orderType;
    uint256 userId;
    uint256 fillBefore;
    uint256 fillAfter;
}
```

Order showing side, market, price, size, user, and how much of it is filled.

#### Parameters

| Name         | Type      | Description                         |
| ------------ | --------- | ----------------------------------- |
| `isBuy`      | `bool`    | True for buy orders, false for sell |
| `market`     | `address` | Market address                      |
| `price`      | `uint256` | Order price                         |
| `size`       | `uint256` | Order size                          |
| `orderType`  | `uint256` | Type of order                       |
| `userId`     | `uint256` | User identifier                     |
| `fillBefore` | `uint256` | Fill before timestamp               |
| `fillAfter`  | `uint256` | Fill after timestamp                |

***

### PriceLevel

```solidity
struct PriceLevel {
    uint256 size;
    uint256 latestNativeId;
    uint256 latest;
    uint256 fillNext;
}
```

Aggregates all orders at a single price level, tracking total size and sequencing identifiers for fill order.

#### Parameters

| Name             | Type      | Description   |
| ---------------- | --------- | ------------- |
| `size`           | `uint256` | Order size    |
| `latestNativeId` | `uint256` | Numeric value |
| `latest`         | `uint256` | Numeric value |
| `fillNext`       | `uint256` | Numeric value |

***

### Market

```solidity
struct Market {
    uint80 highestBid;
    uint80 lowestAsk;
    uint40 minSize;
    uint24 takerFee;
    uint24 makerRebate;
    bool isAMMEnabled;
    uint112 reserveQuote;
    uint112 reserveBase;
    address quoteAsset;
    address baseAsset;
    uint256 marketId;
    uint256 marketType;
    uint256 scaleFactor;
    uint256 tickSize;
    uint256 maxPrice;
    address creator;
    uint88 createTimestamp;
    uint8 creatorFeeSplit;
}
```

Canonical on-chain market config and state: quotes/base assets, fees, size/tick/price bounds, AMM toggle, reserves, creator info, ids, and creation time.

#### Parameters

| Name              | Type      | Description                   |
| ----------------- | --------- | ----------------------------- |
| `highestBid`      | `uint80`  | Best bid                      |
| `lowestAsk`       | `uint80`  | Best ask                      |
| `minSize`         | `uint40`  | Minimum order size            |
| `takerFee`        | `uint24`  | Taker fee in basis points     |
| `makerRebate`     | `uint24`  | Maker rebate in basis points  |
| `isAMMEnabled`    | `bool`    | Whether AMM is enabled        |
| `reserveQuote`    | `uint112` | Quote reserve (LP)            |
| `reserveBase`     | `uint112` | Base reserve (LP)             |
| `quoteAsset`      | `address` | Quote token address           |
| `baseAsset`       | `address` | Base token address            |
| `marketId`        | `uint256` | Market identifier             |
| `marketType`      | `uint256` | Market type identifier        |
| `scaleFactor`     | `uint256` | Decimal scale for price math. |
| `tickSize`        | `uint256` | Minimum price increment       |
| `maxPrice`        | `uint256` | Upper price bound             |
| `creator`         | `address` | Address parameter             |
| `createTimestamp` | `uint88`  | Numeric value                 |
| `creatorFeeSplit` | `uint8`   | Numeric value                 |

***

### MarketInfo

```solidity
struct MarketInfo {
    address quoteAsset;
    address baseAsset;
    uint256 marketType;
    uint256 highestBid;
    uint256 lowestAsk;
    uint256 scaleFactor;
    uint256 tickSize;
    uint256 maxPrice;
    uint256 minSize;
    uint256 takerFee;
    uint256 makerRebate;
    uint256 reserveQuote;
    uint256 reserveBase;
    bool isAMMEnabled;
}
```

Market’s key info for UIs, like top prices, fees, reserves, and settings.

#### Parameters

| Name           | Type      | Description            |
| -------------- | --------- | ---------------------- |
| `quoteAsset`   | `address` | Quote token address    |
| `baseAsset`    | `address` | Base token address     |
| `marketType`   | `uint256` | Market type identifier |
| `highestBid`   | `uint256` | Best bid (widened)     |
| `lowestAsk`    | `uint256` | Best ask (widened)     |
| `scaleFactor`  | `uint256` | Price scaling factor   |
| `tickSize`     | `uint256` | Price tick size        |
| `maxPrice`     | `uint256` | Max price boundary     |
| `minSize`      | `uint256` | Minimum order size     |
| `takerFee`     | `uint256` | Taker fee (scaled)     |
| `makerRebate`  | `uint256` | Maker rebate (scaled)  |
| `reserveQuote` | `uint256` | Quote LP reserve       |
| `reserveBase`  | `uint256` | Base LP reserve        |
| `isAMMEnabled` | `bool`    | Whether AMM is enabled |

***

### TokenMetadata

```solidity
struct TokenMetadata {
    address token;
    uint256 decimals;
    string ticker;
    string name;
}
```

*Token metadata* including address, decimals, ticker, and name.

#### Parameters

| Name       | Type      | Description       |
| ---------- | --------- | ----------------- |
| `token`    | `address` | Token address     |
| `decimals` | `uint256` | Decimal precision |
| `ticker`   | `string`  | String value      |
| `name`     | `string`  | Name string       |

***

### MarketDetails

```solidity
struct MarketDetails {
    uint256 marketId;
    uint256 marketType;
    uint256 scaleFactor;
    uint256 tickSize;
    uint256 maxPrice;
    uint256 minSize;
    uint256 takerFee;
    uint256 makerRebate;
}
```

Set parameters for a market: ids, scale/tick/max price, min size, and fee schedule.

#### Parameters

| Name          | Type      | Description            |
| ------------- | --------- | ---------------------- |
| `marketId`    | `uint256` | Market identifier      |
| `marketType`  | `uint256` | Market type identifier |
| `scaleFactor` | `uint256` | Price scaling factor   |
| `tickSize`    | `uint256` | Minimum tick           |
| `maxPrice`    | `uint256` | Upper price bound      |
| `minSize`     | `uint256` | Minimum order size     |
| `takerFee`    | `uint256` | Taker fee (scaled)     |
| `makerRebate` | `uint256` | Maker rebate (scaled)  |

***

### Action

```solidity
struct Action {
    bool isRequireSuccess;
    uint256 action;
    uint256 param1;
    uint256 param2;
    uint256 param3;
}
```

Single instruction inside a batch (e.g., place/cancel/replace); `isRequireSuccess` gates revert behavior, `action` op-code with up to three numeric params.

#### Parameters

| Name               | Type      | Description                                 |
| ------------------ | --------- | ------------------------------------------- |
| `isRequireSuccess` | `bool`    | If true, revert batch on sub-action failure |
| `action`           | `uint256` | Opcode (e.g., place/cancel/replace/market)  |
| `param1`           | `uint256` | First numeric parameter                     |
| `param2`           | `uint256` | Second numeric parameter.                   |
| `param3`           | `uint256` | Third numeric parameter.                    |

***

### Batch

```solidity
struct Batch {
    address market;
    Action[] actions;
    uint256 options;
}
```

Collection of `Action` to execute atomically on one market, with an `options` bitfield for execution flags.

#### Parameters

| Name      | Type       | Description                                 |
| --------- | ---------- | ------------------------------------------- |
| `market`  | `address`  | Target market for all actions in the batch. |
| `actions` | `Action[]` | Ordered list of sub-operations.             |
| `options` | `uint256`  | Bitfield flags                              |

***

### Parameters

```solidity
struct Parameters {
    address quoteAsset;
    address baseAsset;
    uint256 marketId;
    uint256 marketType;
    uint256 scaleFactor;
    uint256 tickSize;
    uint256 maxPrice;
}
```

Holds market-level configuration such as quote/base asset addresses, market ID, scaling factor, tick size, and maximum price

#### Parameters

| Name          | Type      | Description             |
| ------------- | --------- | ----------------------- |
| `quoteAsset`  | `address` | Quote token address     |
| `baseAsset`   | `address` | Base token address      |
| `marketId`    | `uint256` | Market identifier       |
| `marketType`  | `uint256` | Market type identifier  |
| `scaleFactor` | `uint256` | Price scaling factor    |
| `tickSize`    | `uint256` | Minimum price increment |
| `maxPrice`    | `uint256` | Upper bound for ticks   |

***

### LaunchpadMarket

```solidity
struct LaunchpadMarket {
    uint112 virtualNativeReserve;
    uint112 virtualTokenReserve;
    uint256 k;
    address creator;
    address market;
    uint88 createTimestamp;
}
```

State of a launchpad token market.&#x20;

#### Parameters

| Name                   | Type      | Description                     |
| ---------------------- | --------- | ------------------------------- |
| `virtualNativeReserve` | `uint112` | Bonding-curve native reserve    |
| `virtualTokenReserve`  | `uint112` | Bonding-curve token reserve     |
| `k`                    | `uint256` | Constant product                |
| `creator`              | `address` | Creator address (for fee split) |
| `market`               | `address` | Market address after graduation |
| `createTimestamp`      | `uint88`  | Creation time                   |

***

### LaunchpadParams

```solidity
struct LaunchpadParams {
    uint112 launchpadInitialNativeSupply;
    uint256 launchpadFee;
    uint256 launchpadCreatorFeeSplit;
    uint256 graduatedMinSize;
    uint256 graduatedTakerFee;
    uint256 graduatedMakerRebate;
    uint256 graduatedCreatorFeeSplit;
}
```

Launchpad settings: initial native supply, fees/splits, and “graduated” market params after launch.

#### Parameters

| Name                           | Type      | Description                        |
| ------------------------------ | --------- | ---------------------------------- |
| `launchpadInitialNativeSupply` | `uint112` | Initial virtual native liquidity.  |
| `launchpadFee`                 | `uint256` | Fee factor (base 100\_000)         |
| `launchpadCreatorFeeSplit`     | `uint256` | Creator share of fees              |
| `graduatedMinSize`             | `uint256` | Post-graduation min size           |
| `graduatedTakerFee`            | `uint256` | Post-graduation taker fee (scaled) |
| `graduatedMakerRebate`         | `uint256` | Post-graduation maker rebate       |
| `graduatedCreatorFeeSplit`     | `uint256` | Creator fee split after graduation |

***

### PendingExpiredFeeClaim

```solidity
struct PendingExpiredFeeClaim {
    uint256 deadline;
    address[] tokens;
    uint256[] amounts;
}
```

Queued claim of expired fees for a user: deadline plus token list and amounts.

#### Parameters

| Name       | Type        | Description                               |
| ---------- | ----------- | ----------------------------------------- |
| `deadline` | `uint256`   | Earliest time this claim can be executed. |
| `tokens`   | `address[]` | Tokens included in the claim.             |
| `amounts`  | `uint256[]` | Snapshotted amounts at queue time.        |

***
