> ## 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

> [accordion] Money is bigint in USDC base units
>
> 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] Distances are micro-basis-points
>
> `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] Rates are basis points
>
> `entryFeeBps`, `exitFeeBps` and friends. `ONE_HUNDRED_PCT_BPS` is `10_000n`.

> [accordion] Addresses are hex on the instruction boundary
>
> 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] A quote's age is counted in slots
>
> 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](https://docs.rekt.money/sdk/quotes.md#what-the-program-checks).

## The surface, by area

| Area | Exports |
| - | - |
| **Addresses** | `PROGRAM_ID`, `configPda`, `vaultPda`, `marketPda`, `traderPda`, `assetId`, `assetSymbol`, `toHex`, `toBase58`, `derive`, `declaredPdas` |
| **Decoding** | `decodeConfig`, `decodeVault`, `decodeMarket`, `decodeTraderAccount`, `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](https://docs.rekt.money/sdk/orders.md#the-timing-settings). |
| **Pool gauges** | `vaultGauges` |
| **The queue** | `capitalPda`, `queuePda`, `decodeCapitalState`, `decodeQueue`, `decodeQueueEntry`, `queuePosition`, `payQueue`, `withCapitalRiders`, `capitalActive`. See [how a win is paid](https://docs.rekt.money/liquidity.md#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`, `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` |
| **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`), `addCollateralFor` and `requestCloseFor` (either feed kind: they add the governance table a feed-kind-3 market needs), `requestCloseGovTableFor`, `lazerCommitRemaining`, `addCollateralForMode` (kind 2 only), `addCollateralCommit`, `provePrice`, `lastResortTableRemaining`, `settleRemainingAccounts`, `buildInstruction`, `decodeInstructionData` |
| **Sending** | `submitBenchmarkQuoted`, `composeBenchmarkTransaction`, `BENCHMARK_QUOTED_LAYOUT`, `pricingRemainingAccounts`, `priceAccountsFor` (the remaining accounts of an open, an add, a settle or a take-profit: the sysvar, the governance table and the market's fee-terms account, each where the program reads it, on feed kind 2 and 3), `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) |
| **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](https://docs.rekt.money/sdk/settling.md#5-confirm-then-read-what-the-close-paid-from-its-own-transaction). |
| **Oracle** | `FEED_KIND`, `settlementIdentity`, `benchmarkFeedIdOf`, `benchmarkSymbolOf` |
| **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.

`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,
  USDC_DECIMALS,
} from '@rekt-trading/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,
  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](https://docs.rekt.money/how-it-works.md#the-target).

> [!WARNING]
>
> **`LAUNCH` is not a source of truth.** It holds the package's default values, and they are not the
> venue's. Every field in it is governed and can move on chain. Show nothing, settle nothing, quote
> nothing and gate nothing against it — read the config account.

## 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 | only on a market with trading hours |
| `lastResort` | 5 | nobody | yes | no |
| `borrowSpent` | 6 | nobody | yes | no |

`voluntary` starts with the owner's `request_close`, and the settle that completes it may be sent by
anyone. `borrowSpent` closes a position that funding has used up; it cannot occur on a position that
opened at a funding rate of 0. `userExpiry` and `tenorExpiry` start with a `mark_expiry` that anyone may send from the
deadline. See [settling](https://docs.rekt.money/sdk/settling.md#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 the last-resort grace (`config.lastResortGraceS`, which falls back
to the program's default of 24 hours when unset) has elapsed. It pays a live position its stake back with the
exit fee waived. See [the no-price close](https://docs.rekt.money/sdk/settling.md#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.

## 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-trading/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-trading/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. A live
cluster is read 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.

> [card] [Session keys](https://docs.rekt.money/sdk/sessions.md)
>
> Who signs a trade, and the session-key delegate's three clocks.

> [card] [Risk disclosure](https://docs.rekt.money/risk.md)
>
> What can go wrong, for traders and for the liquidity pool.


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