> ## Documentation Index
> Fetch the complete documentation index at: https://docs.rekt.money/llms.txt
> Use this file to discover all available pages before exploring further.

# Reference

> Units, conventions, the exported surface by area, and the constants a client needs.

## Units and conventions

<AccordionGroup>
  <Accordion title="Money is bigint in USDC base units" icon="dollar-sign">
    Six decimals. `1_000_000n` is one dollar. Division truncates toward zero, matching the Rust
    engine exactly. Parse user text with `parseUsdc`; never through `Number`.
  </Accordion>

  <Accordion title="Distances are micro-basis-points" icon="ruler">
    `barrierMicroBp` and `takeProfitMicroBp` are signed distances from entry, in millionths of a
    basis point. `MICRO_PER_BP` is the conversion. Use `levels()` to turn them into prices rather
    than doing the arithmetic yourself.
  </Accordion>

  <Accordion title="Rates are basis points" icon="percent">
    `entryFeeBps`, `exitFeeBps` and friends. `ONE_HUNDRED_PCT_BPS` is `10_000n`.
  </Accordion>

  <Accordion title="Addresses are hex on the instruction boundary" icon="hashtag">
    Account maps take 32-byte hex strings. `toHex(publicKey)` converts in, `toBase58(hex)` converts
    out. Everything you read back from a decoded account is hex.
  </Accordion>

  <Accordion title="A quote's age is counted in slots" icon="clock">
    A signed quote's `ageSlots` is `Clock.slot` minus the slot the quote was published in, and its
    `ageMs` is that age counted at 400 ms a slot. The program bounds the first by
    `market.maxOracleAgeSlots` and the second by `market.maxOracleAgeMs`. See
    [quotes](/sdk/quotes#what-the-program-checks).
  </Accordion>
</AccordionGroup>

## The surface, by area

| Area | Exports |
| - | - |
| **Addresses** | `PROGRAM_ID`, `configPda`, `vaultPda`, `marketPda`, `traderPda`, `lpPda`, `ticketPda`, `assetId`, `assetSymbol`, `toHex`, `toBase58`, `derive`, `declaredPdas` |
| **Decoding** | `decodeConfig`, `decodeVault`, `decodeMarket`, `decodeTraderAccount`, `decodeLpAccount`, `decodeRedemptionTicket`, `decodeAccount`, `identifyAccount` |
| **Events** | `decodeEntryFilled`, `decodeOpenVoided`, `decodeCollateralCommitted`, `decodeAddReversed`, `decodeCloseRequested`, `decodeExpiryMarked`, `decodeKnockoutBeforeAdd`, `decodeSettlementReceipt`, `decodeSettlementPriced`, `decodePositionOpened`, `decodePositionStamped`, `decodeTakeProfitSet`, `readTradeHistory`, `reconcile` |
| **Stops** | on `ConfigView`: `oracleFrozen`, `settlesDisabled` |
| **Mode and timing** | `commitOpen`, `addsOn`, `exitAnchors`, `newRules`, `timingInForce`, `completeTiming`, `fillDeadlineSlots`, `exitWindowSlots`, `govTablePda`, `decodeGovTable`. See [orders and closes](/sdk/orders#the-timing-settings). |
| **Pool gauges** | `vaultGauges`, `redemptionValue` |
| **The queue** | `capitalPda`, `queuePda`, `decodeCapitalState`, `decodeQueue`, `decodeQueueEntry`, `queuePosition`, `payQueue`, `withCapitalRiders`, `capitalActive`. See [how a win is paid](/liquidity#how-a-win-is-paid). |
| **Sessions** | `authorizeSession`, `renewSession`, `endSession`, `approveDelegate`, `delegatePda`, `decodeTradeDelegate`, `delegateGates`, `sessionAllowanceGates`, `sessionState`, `sessionStanding`, `decodeTokenDelegate`, `revokeDelegateAllowance`, `decayedSpend`, `DEFAULT_SESSION_TERMS`, `MIN_DELEGATE_DURATION_S`, `MAX_DELEGATE_DURATION_S`, `MIN_DELEGATE_WINDOW_S`, `MAX_DELEGATE_WINDOW_S` |
| **Gates** | `openGates`, `addGates`, `settleGates`, `priceGates`, `redeemGates`, `armGates`, `cancelGates`, `headroom`, `approaching`, `admitted`, `requiredReserve`, `costToOpen`, `collateralForTotal`, `sizeForTotal`, `sizeAddForTotal`, `inEventWindow`, `nextEventWindow`, `openTenorS`, `nextSessionOpenS`, `sessionHeadroomS`, `minSessionTenorS`, `forecastCloseS`, `forecastAdmits`, `quoteParseGates`, `resolveSessionCloseMarginS`, `resolveConfidenceCeilingBp`, `resolveMinHoldSlots`, `holdInForce`, `closableFromSlotOf`, `slotsUntil`, `estimatedSecondsUntil`, `sideRoom`, `benchmarkSourceFloor`, `minWithdrawalDelay`, `effectiveWithdrawalDelay` |
| **Previews** | `openPreview`, `settlePreview`, `levels`, `governedFrom` |
| **Positions** | `phase`, `isUnfilled`, `pendingAdd`, `addTargetSlot`, `addMemo`, `memoIsLive`, `exitTargetSlot`, `exitReason`, `tpFloorSlot`, `heldPositions`, `freeSlots`, `findBySeq`, `samePosition`, `deadlines`, `isPermissionless`, `slotCapacity`, `rentExemptLamports`, `openedSeq`, `landedOpenedSeq`, `loggedReturns`, `SeqReadRefusal` |
| **Instructions** | `ix` (with `ix.open`, `ix.requestClose`, `ix.markExpiry` and `ix.stampBook`), `addCollateralForMode`, `addCollateralCommit`, `provePrice`, `lastResortTableRemaining`, `settleRemainingAccounts`, `buildInstruction`, `decodeInstructionData` |
| **Sending** | `submitBenchmarkQuoted`, `composeBenchmarkTransaction`, `BENCHMARK_QUOTED_LAYOUT`, `pricingRemainingAccounts`, `priceAccountsFor` (the remaining accounts of an open, a settle or a take-profit: the sysvar, the governance table and the market's fee-terms account, each where the program reads it), `withFeeTermsTable`, `benchmarkQuoteView`, `benchmarkWireGates`, `distinctEd25519Signers`, `assertBenchmarkQuoteSelfContained`, `SenderRefusal`, `computeUnitLimit` |
| **Settlement maths** | `settle`, `maxPayout`, `favourableMove`, `isConserving`, `barrierMicroBps`, `takeProfitMicroBps`, `validate` |
| **Errors** | `catalogue`, `errorForCode`, `errorForName`, `retryClassOf`, `RETRY_CLASS_LABEL`, `contextOf`, `ProgramRefusal`, `ADVICE`, `auditErrorCatalogue` |
| **Chain access** | `read`, `readBest`, `readAtSlot`, `readCached`, `slot`, `providerStatus`, `AllProvidersFailed`, `SlotNotReached`, `getTransactionV1` (a transaction read that survives a version `@solana/web3.js` cannot parse), `memoReader` (read each landed transaction once), `ProgramLogScan` (one cursor-and-memo scan of the program's logs) |
| **Confirming** | `confirmSignature`, `connectionSignatureReader`, `connectionSignaturePush` (an optional push hint), `poolSignatureReader`, `receiptOf`, `landedTxOf`, `decodeVenueEvent`, `venueEventsNamed`, `minuteEventsNamed`, `closedTradesInTransaction`, `readSettlementForSeq`, and the `Stage` / `Ending` / `LandedTx` / `Receipt` types. See [settling](/sdk/settling#5-confirm-then-read-what-the-close-paid-from-its-own-transaction). |
| **Oracle** | `FEED_KIND`, `settlementIdentity`, `benchmarkFeedIdOf` |
| **Markets** | `listedRoster` (which markets exist on the cluster, read from chain), `listedOrExpected`, `rosterSymbols`, `chooseMarketTable` (the market's own lookup table, else `SHARED_KIND2_TABLE`, each checked), `marketTableCandidates`, `resolveMarketTable`, `marketTableCheckSized`, `marketTableMinAddresses`, `marketTableRefusalSized`, `marketCalendarFor`, `calendarWindows`, `describeCalendar`, `sessionMarginRefusal`, `CALENDAR_FIT` |
| **Availability** | `availability`, `forceCloseAt`, `ALWAYS_OPEN` |
| **Seam** | `Client`, `ChainSource`, `Action`, `LocalnetSource` |

<Note>
  **The price a market settles on is the signed quote's, in US-dollar units.** A chart drawn from
  one exchange's spot price is a different fact from the price the program verifies. Ask
  `settlementIdentity(market)` which one a market settles on.
</Note>

`llms.txt` ships inside the package and is the whole surface, flat, in reading order — generated,
so it cannot drift.

## Constants a client uses

```ts theme={"dark"}
import {
  APPROACHING,
  CLOSE_REASON_BY_CODE,
  CLOSE_REASON_CODE,
  FAVOURABLE_CLOSE_REASONS,
  INITIAL_POSITION_SLOTS,
  MICRO_PER_BP,
  MIN_HOLD_SLOTS,
  ONE_HUNDRED_PCT_BPS,
  PACKET_LIMIT_BYTES,
  PROGRAM_ID,
  RUNG_FLOOR_BPS,
  TICKET_VALIDITY_S,
  USDC_DECIMALS,
} from '@rekt/1000x';

export const constants = {
  programId: PROGRAM_ID,
  rungFloorBps: RUNG_FLOOR_BPS,            // 20_000 = 2.00x; the tightest take-profit priced at all
  usdcDecimals: USDC_DECIMALS,
  microPerBp: MICRO_PER_BP,
  hundredPercentBps: ONE_HUNDRED_PCT_BPS,
  freshAccountSlots: INITIAL_POSITION_SLOTS, // the default, 12; a client may ask for 1..=12
  minimumHoldSlots: MIN_HOLD_SLOTS,        // the floor; the hold in force is resolveMinHoldSlots(config.minHoldSlots)
  favourableCloses: FAVOURABLE_CLOSE_REASONS, // {voluntary, takeProfit} — NOT the whole gated set
  closeReasonCode: CLOSE_REASON_CODE,
  closeReasonName: CLOSE_REASON_BY_CODE,
  ticketValidityS: TICKET_VALIDITY_S,      // launch value; governed, may be lengthened, never shortened
  packetLimitBytes: PACKET_LIMIT_BYTES,    // one Solana packet; measured on the SIGNED transaction
  gateWarnBand: APPROACHING,
};
```

<Note>
  **The take-profit is a floor, not a ladder.** Any multiple at or above `RUNG_FLOOR_BPS` is
  admitted, up to the payout cap. The presets an interface offers are
  `presetRungsBps(rungCeilingBps(market, config.params))`, computed from the live cap; the `RUNGS`
  export is not the preset list. See [how the product works](/how-it-works#the-rung).
</Note>

<Warning>
  **`LAUNCH` is not a source of truth.** It exists so an interface can paint something before its
  first fetch resolves. Every field in it is governed and can move on chain. Settle nothing, quote
  nothing and gate nothing against it — read the config account.
</Warning>

## Close reasons

| Name | Code | Who must sign | A stranger may submit it | Minimum hold applies |
| - | - | - | - | - |
| `voluntary` | 0 | the owner **or their session delegate** (the request) | yes, once the owner has requested it | yes |
| `knockout` | 1 | nobody | yes | no |
| `takeProfit` | 2 | nobody | yes | yes |
| `userExpiry` | 3 | nobody | yes | yes |
| `tenorExpiry` | 4 | nobody | yes | no |
| `lastResort` | 5 | nobody | yes | no |

`voluntary` starts with the owner's `request_close`, and the settle that completes it may be sent by
anyone. `userExpiry` and `tenorExpiry` start with a `mark_expiry` that anyone may send from the
deadline. See [settling](/sdk/settling#request-or-mark-then-settle).

`lastResort` carries no quote. It is legal only while no fresh price exists and the oracle is not
frozen, and on one of two grounds: the market is dark (no posted price for 24 hours), or the
position's finite frozen tenor plus `config.lastResortGraceS` has elapsed. It pays a live position
its stake back with the exit fee waived. See [the no-price close](/sdk/settling#the-no-price-close).

<Warning>
  `FAVOURABLE_CLOSE_REASONS` is `{voluntary, takeProfit}`. It is not the set the minimum hold
  applies to — a client testing membership in it before offering a close on a user timer will offer
  one the chain refuses with `MinimumHoldNotMet` (6103).

  A session delegate is not a stranger: it is the owner's own key, and no key outside that pair can
  take a `voluntary` close. Every close reason is refused while `config.settlesDisabled` is set.
</Warning>

## Market availability

Never a boolean. A boolean cannot distinguish "closed on its own calendar" from "the oracle died",
and those need opposite handling.

```ts theme={"dark"}
import { type MarketAvailability } from '@rekt/1000x';

export function badge(a: MarketAvailability): { text: string; tone: 'ok' | 'wait' | 'bad' } {
  switch (a.state) {
    case 'open':
      return { text: 'Open', tone: 'ok' };
    case 'closed':
      return { text: `Closed — ${a.reason}`, tone: 'wait' };
    case 'closing-soon':
      return { text: 'Closing soon — opens refused', tone: 'wait' };
    case 'halted':
      return { text: `Halted — ${a.reason}`, tone: 'bad' };
  }
}
```

A stale feed at 02:00 on a closed market is **correct**; the same staleness while the market is open
is an outage. `availability()` consults the session before it is allowed to call anything an oracle
failure.

`closing-soon` means opens are refused and `forceCloseAt` is when open positions end. A market whose
feed has stopped answering during an open session reads `halted`, reason `oracle`.

On a market with trading hours, `opensAt` comes from the market's own calendar (`Market.sessions`),
the calendar the program refuses opens against. `nextSessionOpenS(market, now)` gives the same
instant directly, and `openTenorS(config, market, now)` gives the life an open would be given now —
shorter than the venue tenor near the close, since a position ends before its session does.
Opens stop before the close: at `now + sessionHeadroomS(market, now) − market.sessionBufferS −
minSessionTenorS()`, the instant `openTenorS` turns `'too-late'`.

**Chain time.** The program judges every deadline against `Clock.unix_timestamp` and counts every age in
slots. Read the chain's time, never your machine's: `chainNowSeconds(connection)`, or the Clock sysvar.

## The chain seam

`Client` is a reader over a `ChainSource`, which is an interface: clock, account bytes, token
balances, and a way to send actions. It exists so the same client code runs against different
backends without changing.

```ts theme={"dark"}
import { type AccountKey, type ChainSource } from '@rekt/1000x';

// The seam, in outline. `addressFor` matters more than it looks: `position.market` is an ADDRESS,
// so a client holding two markets cannot tell which one a position belongs to without asking the
// source to name them.
export type Seam = Pick<ChainSource, 'kind' | 'addressFor' | 'clock' | 'account' | 'send'>;
export type Key = AccountKey;
```

The source that ships with the package is `LocalnetSource`, which runs the program's own logic out
of process — no validator, no deploy — and is what the SDK's test suite drives. Reading a live
cluster today is done directly, as shown throughout these pages: derive the PDA, read the account,
decode it.

## Honesty about coverage

The package states its own boundary rather than implying coverage it does not have. Its settlement
arithmetic, account layouts, refusals and instruction encoding are checked against the program
itself, by golden vectors emitted from the engine. A handful of runtime concerns — the things only a
real validator can exercise — are listed explicitly in the readme shipped inside the package, and
that list is the edge of what has been proven.

<CardGroup cols={2}>
  <Card title="Session keys" icon="key" href="/sdk/sessions">
    Who signs a trade, and the session-key delegate's three clocks.
  </Card>

  <Card title="Risk disclosure" icon="triangle-exclamation" href="/risk">
    What can go wrong, for traders and for the liquidity pool.
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.