# Contract ABIs Documentation

### Table of Contents

* Core Contracts
  * Xbit
  * Voucher
  * Sortes
  * Charity
  * Locker
* Token Contracts
  * Xexp
  * Xlpt
  * ERC20
* Utility Contracts
  * Maintainable
  * Cored
  * Coordinator
* Data Structures

***

### Core Contracts

#### Xbit Contract

**Location:** `v3xbit/api/XbitAbi.ts`

The main gaming contract that handles token deposits, withdrawals, and play mechanics using Chainlink VRF for randomness.

**Events**

**TokenDeposited**

```solidity
event TokenDeposited(address tokenAddress, uint256 tokenAmount, uint256 lpAmount, address user)
```

Emitted when a user deposits tokens into the pool.

**TokenWithdrawRequested**

```solidity
event TokenWithdrawRequested(
  tuple(
    uint256 withdrawId,
    address tokenAddress,
    uint256 lpAmount,
    uint256 timestamp,
    uint256 feeLpAmount,
    uint256 feeTokenAmount,
    address user
  ) request
)
```

Emitted when a user requests to withdraw tokens from the pool.

**TokenWithdrawExecuted**

```solidity
event TokenWithdrawExecuted(
  address tokenAddress,
  uint256 tokenAmount,
  uint256 lpAmount,
  uint256 feeTokenAmount,
  address user
)
```

Emitted when a withdrawal is executed.

**PlayRequested**

```solidity
event PlayRequested(
  tuple(
    bool fulfilled,
    uint256 playId,
    uint256 blockNumber,
    uint256 blockTimestamp,
    address player,
    address inputToken,
    uint256 inputAmount,
    uint256 repeats,
    address outputToken,
    uint256 requestId,
    uint256 tableTag,
    uint256[] randomWords,
    uint256[] outcomeLevels,
    uint256 outputTotalAmount,
    uint256 outputXexpAmount
  ) status,
  uint256 maintainerAmount,
  uint256 donationAmount
)
```

Emitted when a play is requested.

**PlayFulfilled**

```solidity
event PlayFulfilled(
  tuple(
    bool fulfilled,
    uint256 playId,
    uint256 blockNumber,
    uint256 blockTimestamp,
    address player,
    address inputToken,
    uint256 inputAmount,
    uint256 repeats,
    address outputToken,
    uint256 requestId,
    uint256 tableTag,
    uint256[] randomWords,
    uint256[] outcomeLevels,
    uint256 outputTotalAmount,
    uint256 outputXexpAmount
  ) status
)
```

Emitted when VRF fulfills a play request with random words.

**User Functions**

**deposit**

```solidity
function deposit(address tokenAddress, uint256 tokenAmount) external returns (uint256 lpAmount)
```

Deposits tokens into the pool and receives LP tokens in return.

**requestWithdraw**

```solidity
function requestWithdraw(address tokenAddress, uint256 lpAmount) external
```

Requests to withdraw tokens from the pool by burning LP tokens.

**executeWithdraw**

```solidity
function executeWithdraw() external
```

Executes an immediate withdrawal request for the caller.

**play**

```solidity
function play(
  address player,
  address inputToken,
  uint256 inputAmount,
  uint256 repeats,
  address outputToken,
  tuple(uint8[] relatives, uint256[] mExpectations, uint256[] mRewards, uint256 tag) table
) external returns (uint256 playId)
```

Initiates a game play with specified tokens and probability table.

**listPlayIds**

```solidity
function listPlayIds(address player) external view returns (uint256[] playIds)
```

Lists all play IDs for a given player.

**getPlayStatusById**

```solidity
function getPlayStatusById(uint256 playId) external view returns (PlayStatus status)
```

Gets the detailed status of a specific play by ID.

**getProbabilityTableById**

```solidity
function getProbabilityTableById(uint256 playId) external view returns (ProbabilityTable table)
```

Gets the probability table used for a specific play.

**getLp**

```solidity
function getLp(address token) public view returns (address lp)
```

Gets the LP token address for a given token.

**setDonation**

```solidity
function setDonation(address _donation) external
```

Sets the donation contract address.

**Admin Functions (xbitAdminAbi)**

Additional admin-only functions include:

* `setChainlinkSubscription`: Configure Chainlink VRF parameters
* `listValidTokens`: List all valid input and output tokens
* `addValidInputToken`: Add a token as valid input with lower bound
* `addValidOutputToken`: Add a token as valid output with LP
* `addSwapPair`: Configure swap pairs with fees
* `pause`: Pause/unpause the contract
* Plus all functions from `maintainableAbi`

***

#### Voucher Contract

**Location:** `v3xbit/api/VoucherAbi.ts`

Manages vouchers that can be issued, transferred, and used for gameplay.

**Events**

**VoucherIssued**

```solidity
event VoucherIssued(
  uint256 voucherId,
  address inputToken,
  uint256 inputAmount,
  uint256 repeats,
  uint256 quantity
)
```

Emitted when vouchers are issued.

**VoucherTransferred**

```solidity
event VoucherTransferred(uint256[] voucherIds, uint256[] quantities, address newOwner)
```

Emitted when vouchers are transferred to a new owner.

**PlayRequested**

```solidity
event PlayRequested(address player, uint256 voucherId, address outputToken, uint256 playId)
```

Emitted when a play is requested using a voucher.

**Functions**

**issue**

```solidity
function issue(
  address inputToken,
  uint256 inputAmount,
  uint256 repeats,
  uint256 quantity
) external returns (uint256 voucherId)
```

Issues new vouchers with specified parameters.

**getDetail**

```solidity
function getDetail(uint256 voucherId) external view returns (VoucherDetail voucherDetail)
```

Gets the details of a voucher by its ID.

**getId**

```solidity
function getId(
  address inputToken,
  uint256 inputAmount,
  uint256 repeats
) external pure returns (uint256 voucherId)
```

Calculates the voucher ID from its parameters.

**get**

```solidity
function get(address owner, uint256 voucherId) external view returns (uint256 quantity)
```

Gets the quantity of a specific voucher owned by an address.

**list**

```solidity
function list(address owner) external view returns (uint256[] voucherIds, uint256[] quantities)
```

Lists all vouchers and their quantities for an owner.

**transfer**

```solidity
function transfer(uint256[] voucherIds, uint256[] quantities, address newOwner) external
```

Transfers vouchers to a new owner.

**play**

```solidity
function play(
  address player,
  uint256 voucherId,
  address outputToken,
  tuple(uint8[] relatives, uint256[] mExpectations, uint256[] mRewards, uint256 tag) table
) external returns (uint256 playId)
```

Initiates a play using a voucher.

**Admin Functions (voucherAdminAbi)**

* `setXbitAddress`: Set the Xbit contract address
* `nominalBalance`: Get the nominal balance of a token
* `withdraw`: Withdraw tokens from the contract
* Plus all functions from `maintainableAbi`

***

#### Sortes Contract

**Location:** `v3xbit/api/SortesAbi.ts`

The donation and voting system that allows converting XEXP to GOOD tokens and managing donations.

**Events**

**DonationInitiated**

```solidity
event DonationInitiated(Donation donation)
```

Emitted when a new donation is initiated.

**DonationVoted**

```solidity
event DonationVoted(
  address indexed user,
  uint256 donationId,
  uint256 playId,
  uint256 xexpAmount,
  uint256 usdAmount,
  uint256 goodAmount
)
```

Emitted when a user votes for a donation.

**DonationClosed**

```solidity
event DonationClosed(Donation donation)
```

Emitted when a donation is closed.

**GoodConverted**

```solidity
event GoodConverted(address indexed user, uint256 xexpAmount, uint256 goodAmount)
```

Emitted when XEXP is converted to GOOD.

**Functions**

**initiateDonation**

```solidity
function initiateDonation(address receiver) external returns (uint256 donationId)
```

Initiates a new donation with GOOD spent. Returns the donation ID.

**getDonationsTotal**

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

Gets the total number of donations.

**listDonations**

```solidity
function listDonations(address user) external view returns (Donation[] donations)
```

Lists all donations initiated by a user.

**getDonations**

```solidity
function getDonations(uint256[] ids) external view returns (Donation[] donations)
```

Gets multiple donations by their IDs.

**voteDonation**

```solidity
function voteDonation(
  uint256 donationId,
  uint256 playId,
  uint256 xexpAmount
) external returns (uint256 usdAmount, uint256 goodAmount)
```

Votes for a donation by converting XEXP to GOOD in a locker.

**closeDonation**

```solidity
function closeDonation(uint256 donationId) external
```

Closes a donation. Must be called by the initiator.

**amm**

```solidity
function amm(uint256 xexpAmount) external view returns (uint256 goodAmount)
```

Calculates the amount of GOOD that would be received for a given XEXP amount.

**convertGoodAndLock**

```solidity
function convertGoodAndLock(uint256 xexpAmount) external returns (uint256 goodAmount)
```

Converts XEXP to GOOD at current rate without voting.

**Admin Functions (sortesAdminAbi)**

* `setupParams`: Configure contract parameters
* `getParams`: Get current parameters
* `activate`: Activate/deactivate a donation
* `withdraw`: Withdraw tokens
* `pause`: Pause/unpause the contract
* Plus all functions from `maintainableAbi`

***

#### Charity Contract

**Location:** `v3xbit/api/CharityAbi.ts`

Allows users to play games and automatically donate their XEXP earnings to charity.

**Events**

**PlayResult**

```solidity
event PlayResult(
  uint256 playId,
  uint256 donationId,
  uint256 usdDonatedAmount,
  uint256 goodReceivedAmount
)
```

Emitted when a charity play is completed.

**Functions**

**playWithToken**

```solidity
function playWithToken(
  address inputToken,
  uint256 inputAmount,
  uint256 repeats,
  address outputToken,
  tuple(uint8[] relatives, uint256[] mExpectations, uint256[] mRewards, uint256 tag) table,
  uint256 donationId
) external returns (uint256 playId)
```

Plays with tokens and votes all XEXP earned for the specified donation.

**playWithVoucher**

```solidity
function playWithVoucher(
  uint256 voucherId,
  address outputToken,
  tuple(uint8[] relatives, uint256[] mExpectations, uint256[] mRewards, uint256 tag) table,
  uint256 donationId
) external returns (uint256 playId)
```

Plays with a voucher and votes all XEXP earned for the specified donation.

**Admin Functions (charityAdminAbi)**

* `setupParams`: Configure contract parameters (xbit, voucher, sortes addresses)
* `getParams`: Get current parameters
* Plus all functions from `maintainableAbi`

***

#### Locker Contract

**Location:** `v3xbit/api/LockerAbi.ts`

Manages token locking with time-based decay (half-life) for gradual unlocking.

**Events**

**TokenLocked**

```solidity
event TokenLocked(address indexed user, uint256 tokenAmount, uint256 timestamp)
```

Emitted when tokens are locked for a user.

**TokenClaimed**

```solidity
event TokenClaimed(address indexed user, uint256 claimedAmount, uint256 timestamp)
```

Emitted when a user claims their unlocked tokens.

**Functions**

**lockToken**

```solidity
function lockToken(address user, uint256 tokenAmount) external
```

Transfers tokens into the locker and locks them for a user.

**queryToken**

```solidity
function queryToken(address user) external view returns (
  uint256 lockedAmount,
  uint256 claimableAmount
)
```

Queries the locked and claimable token amounts for a user.

**claimToken**

```solidity
function claimToken(address user) external
```

Claims all claimable tokens for a user.

**getTotalHistory**

```solidity
function getTotalHistory() external view returns (
  uint256 receivedAmount,
  uint256 claimedAmount
)
```

Gets the total history of tokens received and claimed by the contract.

**getUserHistory**

```solidity
function getUserHistory(address user) external view returns (
  uint256 receivedAmount,
  uint256 claimedAmount
)
```

Gets the history of tokens received and claimed by a specific user.

**Admin Functions (lockerAdminAbi)**

* `setupParams`: Configure parameters (token, halfLife, globalLockDeadline)
* `getParams`: Get current parameters
* Plus all functions from `maintainableAbi`

***

### Token Contracts

#### Xexp Token

**Location:** `v3xbit/api/XexpAbi.ts`

The experience token that combines ERC20, Cored, and mint/burn capabilities.

**Functions**

Includes all functions from:

* `erc20Abi` (standard ERC20 interface)
* `coredAbi` (core address management)

Plus additional functions:

**mint**

```solidity
function mint(address account, uint256 amount) external
```

Mints new XEXP tokens to an account.

**burn**

```solidity
function burn(address account, uint256 amount) external
```

Burns XEXP tokens from an account.

***

#### Xlpt Token

**Location:** `v3xbit/api/XlptAbi.ts`

Liquidity provider token with conversion utilities.

**Events**

**Minted**

```solidity
event Minted(address account, uint256 amount)
```

Emitted when LP tokens are minted.

**Burned**

```solidity
event Burned(address account, uint256 amount)
```

Emitted when LP tokens are burned.

**Functions**

Includes all functions from:

* `erc20Abi` (standard ERC20 interface)
* `coredAbi` (core address management)

Plus additional functions:

**token2LpAmount**

```solidity
function token2LpAmount(uint256 tokenAmount) external view returns (uint256 lpAmount)
```

Converts token amount to LP token amount.

**lp2TokenAmount**

```solidity
function lp2TokenAmount(uint256 lpAmount) external view returns (uint256 tokenAmount)
```

Converts LP token amount to underlying token amount.

***

#### ERC20 Interface

**Location:** `v3xbit/api/Erc20Abi.ts`

Standard ERC20 token interface with commonly used functions.

**Read Functions**

* `balanceOf(address account)`: Get token balance
* `decimals()`: Get token decimals
* `name()`: Get token name
* `symbol()`: Get token symbol
* `totalSupply()`: Get total supply
* `allowance(address owner, address spender)`: Get allowance

**Write Functions**

* `transfer(address to, uint amount)`: Transfer tokens
* `approve(address spender, uint256 amount)`: Approve spending
* `mint(address account, uint256 amount)`: Mint new tokens

***

### Utility Contracts

#### Maintainable

**Location:** `v3xbit/api/MaintainableAbi.ts`

Simple access control pattern for contract maintenance.

**Functions**

**maintainer**

```solidity
function maintainer() view returns (address)
```

Gets the current maintainer address.

**setMaintainer**

```solidity
function setMaintainer(address newMaintainer) public
```

Sets a new maintainer address.

***

#### Cored

**Location:** `v3xbit/api/CoredAbi.ts`

Interface for managing core contract address references.

**Events**

**CoreAddressSet**

```solidity
event CoreAddressSet(address coreAddress)
```

Emitted when the core address is set.

**Functions**

**setCoreAddress**

```solidity
function setCoreAddress(address coreAddress) public
```

Sets the core contract address.

**core**

```solidity
function core() public view returns (address)
```

Gets the current core contract address.

***

#### Coordinator

**Location:** `v3xbit/api/CoordinatorAbi.ts`

Interface for the Chainlink VRF Coordinator (Arbitrum: `0x3C0Ca683b403E37668AE3DC4FB62F4B29B6f7a3e`).

**Events**

**RandomWordsFulfilled**

```solidity
event RandomWordsFulfilled(
  uint256 indexed requestId,
  uint256 outputSeed,
  uint256 indexed subId,
  uint96 payment,
  bool nativePayment,
  bool success,
  bool onlyPremium
)
```

Emitted when random words are fulfilled by the VRF coordinator.

***

### Data Structures

#### ProbabilityTable

Used by Xbit, Charity, and Voucher contracts to define game mechanics.

```typescript
struct ProbabilityTable {
  uint8[] relatives;      // Reward relative to: 0 = pool, 1 = input
  uint256[] mExpectations; // Expectation (1e6 scale), relative to input
  uint256[] mRewards;      // Reward amount (1e6 scale)
  uint256 tag;             // Table identifier
}
```

Solidity tuple representation:

```solidity
tuple(uint8[] relatives, uint256[] mExpectations, uint256[] mRewards, uint256 tag)
```

**Field Details:**

* `relatives[i]`: For level i, reward is relative to pool (0) or input (1)
* `mExpectations[i]`: Absolute expectation = `input_amount * expectation / 1e6`
* `mRewards[i]`: Absolute reward = `reward * (pool_size or input_amount) / 1e6`
* `tag`: Number used to identify the table

***

#### PlayStatus

Used by Xbit to track play state.

```typescript
struct PlayStatus {
  bool fulfilled;
  uint256 playId;
  uint256 blockNumber;
  uint256 blockTimestamp;
  address player;
  address inputToken;
  uint256 inputAmount;
  uint256 repeats;
  address outputToken;
  uint256 requestId;
  uint256 tableTag;
  uint256[] randomWords;      // Filled by VRF
  uint256[] outcomeLevels;    // Filled after VRF
  uint256 outputTotalAmount;  // Filled after VRF
  uint256 outputXexpAmount;   // Proportional to inputAmount * repeats
}
```

Solidity tuple representation:

```solidity
tuple(
  bool fulfilled,
  uint256 playId,
  uint256 blockNumber,
  uint256 blockTimestamp,
  address player,
  address inputToken,
  uint256 inputAmount,
  uint256 repeats,
  address outputToken,
  uint256 requestId,
  uint256 tableTag,
  uint256[] randomWords,
  uint256[] outcomeLevels,
  uint256 outputTotalAmount,
  uint256 outputXexpAmount
)
```

***

#### WithdrawRequest

Used by Xbit to track withdrawal requests.

```typescript
struct WithdrawRequest {
  uint256 withdrawId;      // Starting from 0
  address tokenAddress;    // Token to withdraw
  uint256 lpAmount;        // LP tokens to burn
  uint256 timestamp;       // Request timestamp
  uint256 feeLpAmount;     // Fee in LP tokens
  uint256 feeTokenAmount;  // Fee in underlying tokens
  address user;            // User who requested
}
```

Solidity tuple representation:

```solidity
tuple(
  uint256 withdrawId,
  address tokenAddress,
  uint256 lpAmount,
  uint256 timestamp,
  uint256 feeLpAmount,
  uint256 feeTokenAmount,
  address user
)
```

***

#### Donation

Used by Sortes to track donation campaigns.

```typescript
struct Donation {
  uint256 id;
  address receiver;
  address initiator;
  uint256 currentAmount;
  uint256 startTime;
  uint256 endTime;
  bool isActivated;
  bool isExecuted;
}
```

Solidity tuple representation:

```solidity
tuple(
  uint256 id,
  address receiver,
  address initiator,
  uint256 currentAmount,
  uint256 startTime,
  uint256 endTime,
  bool isActivated,
  bool isExecuted
)
```

***

#### VoucherDetail

Used by Voucher to store voucher information.

```typescript
struct VoucherDetail {
  uint256 id;           // Hash value
  address inputToken;
  uint256 inputAmount;
  uint256 repeats;
}
```

Solidity tuple representation:

```solidity
tuple(uint256 id, address inputToken, uint256 inputAmount, uint256 repeats)
```

***

### Contract Parameters

#### Sortes Parameters

```typescript
struct Parameters {
  address xexp;
  address good;
  address usd;
  address locker;
  uint256 xexpReserved;
  uint256 goodPerDonation;
}
```

Solidity tuple: `tuple(address xexp, address good, address usd, address locker, uint256 xexpReserved, uint256 goodPerDonation)`

***

#### Locker Parameters

```typescript
struct Parameters {
  address token;
  uint256 halfLife;
  uint256 globalLockDeadline;
}
```

Solidity tuple: `tuple(address token, uint256 halfLife, uint256 globalLockDeadline)`

***

#### Charity Parameters

```typescript
struct Parameters {
  address xbit;
  address voucher;
  address sortes;
}
```

Solidity tuple: `tuple(address xbit, address voucher, address sortes)`

***

### Usage Examples

#### Depositing Tokens

```typescript
// Approve Xbit contract to spend tokens
await token.approve(xbitAddress, amount);

// Deposit tokens and receive LP tokens
const lpAmount = await xbit.deposit(tokenAddress, amount);
```

#### Playing a Game

```typescript
// Define probability table
const table = {
  relatives: [0, 1],           // Level 0: pool relative, Level 1: input relative
  mExpectations: [500000, 1000000], // 50% and 100% of input
  mRewards: [1000000, 2000000],     // Rewards at 1e6 scale
  tag: 1
};

// Play the game
const playId = await xbit.play(
  playerAddress,
  inputToken,
  inputAmount,
  repeats,
  outputToken,
  table
);

// Check play status
const status = await xbit.getPlayStatusById(playId);
if (status.fulfilled) {
  console.log('Play completed:', status);
}
```

#### Using Vouchers

```typescript
// Issue vouchers
const voucherId = await voucher.issue(
  inputToken,
  inputAmount,
  repeats,
  quantity
);

// Play with voucher
const playId = await voucher.play(
  playerAddress,
  voucherId,
  outputToken,
  table
);
```

#### Creating and Voting on Donations

```typescript
// Initiate a donation (costs GOOD)
const donationId = await sortes.initiateDonation(receiverAddress);

// Vote with XEXP after playing
const [usdAmount, goodAmount] = await sortes.voteDonation(
  donationId,
  playId,
  xexpAmount
);

// Close the donation (initiator only)
await sortes.closeDonation(donationId);
```

#### Token Locking and Claiming

```typescript
// Lock tokens for a user
await locker.lockToken(userAddress, tokenAmount);

// Query locked and claimable amounts
const [locked, claimable] = await locker.queryToken(userAddress);

// Claim unlocked tokens
await locker.claimToken(userAddress);
```

***

### Notes

* All amounts are in the token's base units (wei for ETH-like tokens)
* The 1e6 scale is used throughout for probabilities and percentages
* Admin functions require the caller to be the maintainer
* VRF randomness is used for fair game outcomes
* The locker uses half-life decay for gradual token unlocking
