# Jackpot

The main Jackpot contract orchestrates all jackpot operations including ticket purchases, drawings, LP management, and prize distribution.

## State Variables

| Variable               | Type                          | Description                                        |
| ---------------------- | ----------------------------- | -------------------------------------------------- |
| `currentDrawingId`     | `uint256`                     | Current active drawing identifier                  |
| `ticketPrice`          | `uint256`                     | Cost per ticket in USDC (6 decimals)               |
| `normalBallMax`        | `uint8`                       | Maximum value for normal ball numbers              |
| `bonusballMin`         | `uint8`                       | Minimum bonusball range                            |
| `bonusballSoftCap`     | `uint8`                       | Soft cap for bonusball used in pool calculations   |
| `bonusballHardCap`     | `uint8`                       | Hard cap for bonusball (cannot be exceeded)        |
| `referralFee`          | `uint256`                     | Fraction of ticket price to referrers (1e18 scale) |
| `referralWinShare`     | `uint256`                     | Fraction of winnings shared with referrers         |
| `referralFees`         | `mapping(address => uint256)` | Accumulated referral fees per address              |
| `allowTicketPurchases` | `bool`                        | Whether ticket purchases are enabled               |
| `emergencyMode`        | `bool`                        | Whether emergency mode is active                   |

## Structs

### Ticket

```solidity
struct Ticket {
    uint8[] normals;   // 5 unique numbers in [1, ballMax]
    uint8 bonusball;   // 1 number in [1, bonusballMax]
}
```

### DrawingState

```solidity
struct DrawingState {
    uint256 prizePool;           // Total prize available for distribution
    uint256 ticketPrice;         // Cost per ticket (USDC wei)
    uint256 edgePerTicket;       // LP edge amount per ticket
    uint256 referralWinShare;    // % of winnings to referrers
    uint256 referralFee;         // % of ticket price to referrers
    uint256 globalTicketsBought; // Total tickets sold this drawing
    uint256 lpEarnings;          // LP revenue from ticket sales
    uint256 drawingTime;         // Unix timestamp when drawing executes
    uint256 winningTicket;       // Packed winning numbers (after settlement)
    uint8 ballMax;               // Max normal ball number for this drawing
    uint8 bonusballMax;          // Max bonusball for this drawing
    IPayoutCalculator payoutCalculator;
    bool jackpotLock;            // True when drawing in progress
}
```

### ReferralScheme

```solidity
struct ReferralScheme {
    address[] referrers;      // Array of referrer addresses
    uint256[] referralSplit;  // PRECISE_UNIT-scaled weights (must sum to 1e18)
}
```

## Events

### TicketPurchased

```solidity
event TicketPurchased(
    address indexed recipient,
    uint256 indexed currentDrawingId,
    bytes32 indexed source,
    uint256 userTicketId,
    uint8[] normals,
    uint8 bonusball,
    bytes32 referralScheme
);
```

### TicketWinningsClaimed

```solidity
event TicketWinningsClaimed(
    address indexed userAddress,
    uint256 indexed drawingId,
    uint256 userTicketId,
    uint256 matchedNormals,
    bool bonusballMatch,
    uint256 winningsAmount
);
```

### JackpotSettled

```solidity
event JackpotSettled(
    uint256 indexed drawingId,
    uint256 lpEarnings,
    uint256 userWinnings,
    uint8 winningBonusball,
    uint256 winningNumbers,
    uint256 newDrawingAccumulator
);
```

### NewDrawingInitialized

```solidity
event NewDrawingInitialized(
    uint256 indexed drawingId,
    uint256 lpPoolTotal,
    uint256 prizePool,
    uint256 ticketPrice,
    uint256 normalBallMax,
    uint8 bonusballMax,
    uint256 referralWinShare,
    uint256 drawingTime
);
```

## Functions

### buyTickets

Purchase jackpot tickets for the current drawing.

```solidity
function buyTickets(
    Ticket[] memory _tickets,
    address _recipient,
    address[] memory _referrers,
    uint256[] memory _referralSplit,
    bytes32 _source
) external returns (uint256[] memory ticketIds)
```

**Parameters:**

| Name             | Type        | Description                                                 |
| ---------------- | ----------- | ----------------------------------------------------------- |
| `_tickets`       | `Ticket[]`  | Array of ticket structs with normal numbers and bonusball   |
| `_recipient`     | `address`   | Address to receive the minted ticket NFTs                   |
| `_referrers`     | `address[]` | Referrer addresses for fee sharing (can be empty)           |
| `_referralSplit` | `uint256[]` | PRECISE\_UNIT-scaled weights (must sum to 1e18 if provided) |
| `_source`        | `bytes32`   | Identifier for tracking ticket source (telemetry)           |

**Returns:**

| Type        | Description                    |
| ----------- | ------------------------------ |
| `uint256[]` | Array of minted ticket NFT IDs |

**Example:**

```solidity
// Approve USDC first
usdc.approve(address(jackpot), 2e6); // $2 for 2 tickets

// Create tickets
IJackpot.Ticket[] memory tickets = new IJackpot.Ticket[](2);
tickets[0] = IJackpot.Ticket({
    normals: new uint8[](5),
    bonusball: 10
});
tickets[0].normals[0] = 1;
tickets[0].normals[1] = 15;
tickets[0].normals[2] = 23;
tickets[0].normals[3] = 42;
tickets[0].normals[4] = 55;

tickets[1] = IJackpot.Ticket({
    normals: new uint8[](5),
    bonusball: 5
});
tickets[1].normals[0] = 7;
tickets[1].normals[1] = 14;
tickets[1].normals[2] = 21;
tickets[1].normals[3] = 28;
tickets[1].normals[4] = 30;

// Buy tickets with referrer
address[] memory referrers = new address[](1);
referrers[0] = 0x1234...;
uint256[] memory splits = new uint256[](1);
splits[0] = 1e18; // 100% to single referrer

uint256[] memory ticketIds = jackpot.buyTickets(
    tickets,
    msg.sender,
    referrers,
    splits,
    bytes32("my-app")
);
```

***

### claimWinnings

Claim prize winnings for completed drawings.

```solidity
function claimWinnings(uint256[] memory _userTicketIds) external
```

**Parameters:**

| Name             | Type        | Description                                   |
| ---------------- | ----------- | --------------------------------------------- |
| `_userTicketIds` | `uint256[]` | Array of ticket NFT IDs to claim winnings for |

**Example:**

```solidity
uint256[] memory myTickets = new uint256[](2);
myTickets[0] = ticketId1;
myTickets[1] = ticketId2;

jackpot.claimWinnings(myTickets);
// USDC transferred to msg.sender
// Tickets are burned
```

***

### lpDeposit

Deposit USDC into the prize pool as a liquidity provider.

```solidity
function lpDeposit(uint256 _amountToDeposit) external
```

**Parameters:**

| Name               | Type      | Description                            |
| ------------------ | --------- | -------------------------------------- |
| `_amountToDeposit` | `uint256` | Amount of USDC to deposit (6 decimals) |

**Example:**

```solidity
usdc.approve(address(jackpot), 10000e6); // $10,000
jackpot.lpDeposit(10000e6);
```

***

### initiateWithdraw

Start LP withdrawal process by converting shares to pending withdrawal.

```solidity
function initiateWithdraw(uint256 _amountToWithdrawInShares) external
```

**Parameters:**

| Name                        | Type      | Description                                  |
| --------------------------- | --------- | -------------------------------------------- |
| `_amountToWithdrawInShares` | `uint256` | Amount of LP shares to withdraw (1e18 scale) |

**Example:**

```solidity
// Withdraw 50% of shares
uint256 myShares = lpManager.getLpInfo(msg.sender).consolidatedShares;
jackpot.initiateWithdraw(myShares / 2);
```

***

### finalizeWithdraw

Complete pending LP withdrawals and receive USDC.

```solidity
function finalizeWithdraw() external
```

**Example:**

```solidity
// After drawing completes
jackpot.finalizeWithdraw();
// USDC transferred to msg.sender
```

***

### emergencyWithdrawLP

Emergency withdrawal for LPs when system is stuck.

```solidity
function emergencyWithdrawLP() external
```

**Requirements:**

* Emergency mode must be enabled

**Example:**

```solidity
// Only available in emergency mode
jackpot.emergencyWithdrawLP();
```

***

### emergencyRefundTickets

Refund tickets from the current drawing during emergency mode.

```solidity
function emergencyRefundTickets(uint256[] memory _userTicketIds) external
```

**Parameters:**

| Name             | Type        | Description                   |
| ---------------- | ----------- | ----------------------------- |
| `_userTicketIds` | `uint256[]` | Array of ticket IDs to refund |

**Requirements:**

* Emergency mode must be active
* Tickets must be from current drawing only

***

### claimReferralFees

Claim accumulated referral fees.

```solidity
function claimReferralFees() external
```

**Example:**

```solidity
// Check balance first
uint256 myFees = jackpot.referralFees(msg.sender);

// Claim all fees
jackpot.claimReferralFees();
```

***

### runJackpot

Execute the drawing by requesting randomness from entropy provider.

```solidity
function runJackpot() external payable
```

**Requirements:**

* Drawing time must have passed
* Drawing must not be locked
* Sufficient ETH for entropy fee

**Example:**

```solidity
uint256 fee = jackpot.getEntropyCallbackFee();
jackpot.runJackpot{value: fee}();
```

***

## View Functions

### getDrawingState

Get complete state for a drawing.

```solidity
function getDrawingState(uint256 _drawingId) external view returns (DrawingState memory)
```

**Example:**

```solidity
IJackpot.DrawingState memory state = jackpot.getDrawingState(jackpot.currentDrawingId());
uint256 prizePool = state.prizePool;
uint256 ticketPrice = state.ticketPrice;
```

***

### getReferralScheme

Get referral scheme details.

```solidity
function getReferralScheme(bytes32 _referralSchemeId) external view returns (ReferralScheme memory)
```

***

### checkIfTicketsBought

Check if specific tickets have been purchased.

```solidity
function checkIfTicketsBought(uint256 _drawingId, Ticket[] memory _tickets) external view returns (bool[] memory)
```

***

### getUnpackedTicket

Unpack a packed ticket into normal numbers and bonusball.

```solidity
function getUnpackedTicket(uint256 _drawingId, uint256 _packedTicket) external view returns (uint8[] memory normals, uint8 bonusball)
```

***

### getTicketTierIds

Get prize tier IDs for a list of tickets.

```solidity
function getTicketTierIds(uint256[] memory _ticketIds) external view returns (uint256[] memory tierIds)
```

***

### getDrawingTierPayouts

Get payout amounts for all tiers in a drawing.

```solidity
function getDrawingTierPayouts(uint256 _drawingId) external view returns (uint256[12] memory)
```

***

### getEntropyCallbackFee

Get the ETH fee required to run the jackpot.

```solidity
function getEntropyCallbackFee() external view returns (uint256 fee)
```
