# Rekt > This file is very large and may be truncated. For an index of this content, please refer to https://docs.rekt.money/llms.txt instead. > Rekt runs two products on Solana. Knockout: go long or short at 1000x with a stake you choose; the position ends at its barrier, at your take profit, when you cash out, or at your own timer. Minute is a timed round, built on Knockout, that you cannot close early. Docs for traders and for builders using the SDK. # Counts and daily volume Source: https://docs.rekt.money/api-reference/data/aggregates/counts-and-daily-volume /openapi/data-api.json get /v0/stats Counts by market and by day, and the daily volume series. All time. Poll no more than once every 10 seconds. # Payout queue and no-price closes Source: https://docs.rekt.money/api-reference/data/aggregates/payout-queue-and-no-price-closes /openapi/data-api.json get /v0/capital The payout queue in totals, how long the oldest unpaid settlement has waited, and the closes made when a market had no price, by day. All time. Poll no more than once every 10 seconds. # Referral totals Source: https://docs.rekt.money/api-reference/data/aggregates/referral-totals /openapi/data-api.json get /v0/referral Referral totals: the USDC that referrers have claimed, the number of referrers paid, and the number of linked traders. Totals only. All time. Poll no more than once every 10 seconds. # Volume by market Source: https://docs.rekt.money/api-reference/data/aggregates/volume-by-market /openapi/data-api.json get /v0/markets Settlements, stake and notional of each market. All time. Poll no more than once every 10 seconds. # Duel rounds Source: https://docs.rekt.money/api-reference/data/duel/duel-rounds /openapi/data-api.json get /v0/duel/rounds Duel rounds of the last 48 hours, newest first. A round that is still live is dated by its start. Each entry is a position on Knockout, and shows how Knockout settled it. A page holds at most 100 rounds. # Health and limits Source: https://docs.rekt.money/api-reference/data/health/health-and-limits /openapi/data-api.json get /v0/health How fresh the archive is, and the limits that apply to your requests. Start here. Read the limits from `access`. # Minute rounds Source: https://docs.rekt.money/api-reference/data/minute/minute-rounds /openapi/data-api.json get /v0/minute/rounds Minute rounds of the last 48 hours, newest first. A round that is still open is dated by its open time. A page holds at most 100 rounds. # Ended positions Source: https://docs.rekt.money/api-reference/data/positions/ended-positions /openapi/data-api.json get /v0/positions Positions that ended in the last 48 hours, newest first: settled, or an order that the venue returned. Read a position that is still open from the chain. A page holds at most 100 rows. Page with `beforeSlot`. # One settled trade Source: https://docs.rekt.money/api-reference/data/trades/one-settled-trade /openapi/data-api.json get /v0/trades/{signature} One settled trade of the last 48 hours. An older trade gets `404`, the same answer as an unknown signature. Read an older trade from the chain. # Settled trades Source: https://docs.rekt.money/api-reference/data/trades/settled-trades /openapi/data-api.json get /v0/trades Settled trades of the last 48 hours, newest first. A page holds at most 100 rows. Page with `beforeSlot`. # Feed readiness Source: https://docs.rekt.money/api-reference/prices/feeds/feed-readiness /openapi/prices.json get /v1/readiness Whether each feed can be quoted now, and its market session. A closed session signs no price. # Feeds and signer keys Source: https://docs.rekt.money/api-reference/prices/feeds/feeds-and-signer-keys /openapi/prices.json get /v1/feeds The feeds that the price service signs, its signer keys, and the `feed_id` of each feed. Fetch it once at start-up, not for each request. A market's feed is `market.feeds[0]`. It equals the `feed_id` listed for its symbol. # Service health Source: https://docs.rekt.money/api-reference/prices/health/service-health /openapi/prices.json get /v1/health Whether the service process is alive. It says nothing about whether a feed can be quoted: read `GET /v1/readiness` for that. # A signed quote Source: https://docs.rekt.money/api-reference/prices/quotes/a-signed-quote /openapi/prices.json post /v1/quote A signed quote for one feed. The Knockout program verifies the signatures on chain. Fetch a new quote for each attempt, with a new `idempotency_key`. For a window quote, send `min_slot` and `payload_version: 2`. `409` and `429` are retryable after `retry_after_ms`. Every other `4xx` is not: fix the request. # Changelog Source: https://docs.rekt.money/changelog Every version of the SDK, @rekt-trading/1000x, on npm: what is true in it, what it changes for a client, and what to do. This page lists every version of [`@rekt-trading/1000x`](/sdk/installation) on npm. Each entry says what is true in that version, what it changes for a client, and what to do. ## How versions change The package uses semantic versioning, and its major version is 0. | Step | What it can change | | - | - | | Patch, such as `0.5.1` to `0.5.2` | Behaviour and text. It can add a name. Every exported name and signature stays. | | Minor, such as `0.5.2` to `0.6.0` | Any exported name, signature or behaviour: added, changed or removed. Its entry says what to change. | Install the latest version with `npm install @rekt-trading/1000x@latest`. **0.10.0** 2026-11-29 **Impact for a client: additive, with three changed behaviours.** This version matches the venue upgrade live on mainnet since 2026-11-29 (slot 475,530,060). Every 0.9.0 name stays. * **Book capacity is governed.** `MAX_POSITION_SLOTS` is now the ceiling, 63. New: `DEFAULT_BOOK_SLOT_CAP` (21), the most a book is sized to without the `GovTable`. `initTraderAccount` and `resizeTraderAccount` take an optional last argument, the `GovTable` (`govTablePda()`), to size a book up to the venue's book capacity. The book's rent payer pays the extra slots and gets the rent back at close. `CONFIG_DIAL.bookSlotCap` is the dial. * **A result log refunds its payer.** `decodeGameLog` returns `ringLen` and `recordedPayer`; `gameLogRefundTo(log, bookRentPayer)` names the only `rent_to` that `closeGameLog` accepts. New logs hold 31 results. * **Classic Minute terms are frozen or refused.** `classicOpenFeeTerms` and `openFeeTerms` return `{ kind: 'refused', error: 'ClassicTermsUnavailable' }` where they returned the ordinary terms before. * **New errors:** 6394 `ClassicTermsUnavailable`, 6395 `SideCoverCapReached`. `errorForCode` knows both. * `CONFIG_DIAL.sideCapBps` (13) is a per-side cap that is off; `CapitalStateView.sideCapBps` reads it. * The venue no longer reads the dispersion limit. `dispersionLimitFor` returns what it did; nothing on chain uses it. * **Compute-unit limit:** `resize_trader_account` 3,000 to 4,000. * **Free slots from the chain.** `freePositionSlots(bytes)` and `fetchFreePositionSlots(connection, owner)` return a venue book's `{ exists, capacity, live, free }`; `freeRoundSlots(bytes)` and `fetchFreeRoundSlots(connection, wallet)` do the same for a Minute player's round slots, which classic and Sprint rounds share. The size is the account's own, from its byte length; a slot counts as live until its settle lands. * **A refusal named by the program that raised it.** `refusalFromLogs(logs)` and `refusalOf(err)` read the first `Program failed` line, so a venue `6056 PositionSlotsFull` raised inside another program's CPI is the venue's, not that program's 6056. They return the program, the code, its name from that program's table, the CPI depth and the outer program. * `resolveCommitTimerFloorS` is in the public entry: the commit timer floor in force (`Config.timer_floor_s`, 0 is the default 26 s, held in 10 to 26 s). **Do:** read the free slots just before you build an open, and do not send when `free` is 0. Decode a refusal with `refusalOf`, not with the code alone. **0.9.0** 2026-11-27 **Impact for a client: additive, with two removed governance builders.** This version matches the venue upgrade live on mainnet since 2026-11-26 (slot 474,190,653). Every 0.8.2 name and signature stays except those under Removed, and 0.8.2 keeps working on the upgraded venue. * **A referral link in the first trade.** `setReferral({ referee, payer, referrer })` takes the referrer's wallet, and `set_referral` makes the referrer's record when it does not exist yet (registration open; the wallet exists on chain and is on the curve; the link's payer pays the record's rent). `withReferralLink(trade, { referee, payer, referrer, after })` puts the link into the trade's own transaction. Order: Knockout `init_trader_account`, `set_referral`, the open (`after: 1`); Minute or Sprint `set_referral`, `init_player`, optional `mark_minute_trader`, the round's open (`after: 0`) ([referrals](https://docs.rekt.money/referrals)). * **Error 6393 `ReferralReferrerMissing`:** the referrer wallet named for a new record does not exist on chain. Do not retry; check the address. `errorForCode` knows it. * `register_referral_account` for a wallet whose record already exists succeeds and changes nothing. * **Before a commit** on feed kind 2, 3 or 4, a transaction may also hold one `mark_minute_trader`. * **Result logs count non-wins.** `GameReceiptView` gains `nonwinsBefore` and `nonwinsCounted`. New in the public entry: `isNonwin(status, stake, owed)`, `GAME_LOG_COUNTED_VERSION` (3), `NONWINS_COUNTED`, `NONWINS_MASK`. Act on a count only when the log's `version` is `GAME_LOG_COUNTED_VERSION`; a log at another version restarts its count at its next write. * **Compute-unit limits:** | instruction | 0.8.2 | 0.9.0 | | - | - | - | | `settle`, the ordinary shape | 47,000 | 51,000 | | `settleComputeUnitLimit(shape)`, each dearer shape | | 3,000 to 4,000 more | | `settleComputeUnitLimit()`, the largest shape | 141,000 | 144,000 | | `open_anchored` | 24,000 | 23,000 | | `fill_anchored`, per batch | | 1,000 less | * **Removed:** `ix.initGameConfig` and the compute-unit rows `init_game_config` and `init_referral_config`. The venue no longer has those two instructions. **Do:** install 0.9.0 to link a referred wallet in its first trade, and declare the new `settle` limits. **0.8.2** 2026-11-24 **Impact for a client: additive.** Every 0.8.1 name and signature stays. * **The terms a classic Minute open freezes.** `openFeeTerms(config, market, table, classic)` takes an optional fourth argument for a classic Minute round (a Minute-marked book, not a game): with it, the result is the market's classic slot when the venue would freeze it, and the ordinary terms otherwise. `classicOpenFeeTerms(config, market, table, classic?)` returns the classic slot's terms or `null`. The venue freezes the classic slot only when the fee terms are on, the market's classic register names a slot that is neither `cur` nor a game slot, the table rides writable (`minuteIx.open_round` passes it so; `classic.tableWritable` says otherwise), its entry there is a written shape-1 entry, and the zero-at-flat rule holds at the round's tier (`classic.tier`, 0 for the market's own). Without the fourth argument, `openFeeTerms` answers for a Knockout open, as before. * `classicCurSlot(market)` and `classicPrevSlot(market)` are in the public entry: the classic slot in force and the one before it (0 = none). **Do:** pass the fourth argument when you quote a classic Minute round. SOL, BTC, ETH and HYPE name a classic slot. **0.8.1** 2026-11-23 **Impact for a client: additive.** This version matches the venue upgrade live on mainnet since 2026-11-23 (slot 473,102,828). Every 0.8.0 name and signature stays, and 0.8.0 keeps working on the upgraded venue. * **A classic Minute `open_round` carries the market's `FeeTermsTable` writable** (`minuteIx.open_round` adds it). A market can hold a fee-terms slot for classic Minute rounds (`MarketView.classicRegs`); a round freezes that slot only when the table is writable, and the ordinary terms otherwise. SOL, BTC, ETH and HYPE name one ([how a round is paid](https://docs.rekt.money/minute/how-to-think-about-it)). * **The shipped IDL is the upgraded venue's.** New: `decodeTreasuryLegHeld` and `decodeTreasuryHoldSwept` (a settle holds its treasury leg in the vault while the treasury cannot receive it), `CapitalStateView.treasuryHeld`, and `ix.sweepTreasuryHold` (the config authority's; `computeUnitLimit('sweep_treasury_hold')` is 10,000). `mark_minute_trader` takes two accounts; the venue also accepts the Clock as a third. * `TraderAccountView` gains `gameBump`, meaningful only while bit 2 of `bookFlags` is set. * The exit-fee quote on a fee-terms slot of shape 1 matches the venue to the base unit on a winning close. * **Live terms since 0.8.0**, moved by governed writes: the Knockout line, its loss tax and its loss exit fee; Sprint's round length, its win fee and its no-knockout start. Read them on chain; [Fees and limits](https://docs.rekt.money/limits) and [Sprint](https://docs.rekt.money/minute/sprint) state them. * Decode a program error against the program that failed ([error handling](https://docs.rekt.money/sdk/errors)): the programs reuse the same numbers. **Do:** install 0.8.1 before you open classic Minute rounds: with 0.8.0 a round on SOL, BTC, ETH or HYPE freezes the market's ordinary terms instead of its classic slot. **0.8.0** 2026-11-23 **Impact for a client: additive, with one changed constant.** This version matches the games upgrade of the venue and Minute, live on mainnet since 2026-11-23, and adds Sprint. Every 0.7.0 name and signature stays. * **Sprint**, a short Minute round, live on SOL, BTC and ETH ([guide](https://docs.rekt.money/minute/sprint)): `buildOpenSprint` (Minute 27), `buildOpenSprintSession` (Minute 28), `sprintTrailingAccounts`, `sprintConfigPda`, `decodeSprintConfig`, `sprintPayout`, `sprintBreakEvenPrice`, `feeTermsOfGameArgs`, `refuseOddSprintTicket`, `buildSetSprintConfig` (Minute's config authority) and the constants `SPRINT_TICKET_STEP`, `SPRINT_CONFIG_LEN`, `SPRINT_OPENS_ON`, `GAME_KIND_SPRINT`, `MIN_SPRINT_TIMER_S`, `MAX_SPRINT_TIMER_S`. A Sprint ticket is a whole number of cents: the builders and `buildMinuteInstruction` refuse any other ticket. Compute-unit limits: `open_sprint` 59,000, `open_sprint_session` 70,000, `resize_player` 12,000. * **Games accounts and events:** `decodeGameConfig`, `decodeGameLog`, `gameConfigPda`, `gameLogPda`, `GAME_SPRINT`, `sprintCurSlot`, `sprintPrevSlot`, the `OPEN_SCOPE_*` values with `openScopeIsLegal`, `validateZeroAtFlat`, and the decoders of `GameConfigSet`, `GameTermsSet`, `MarketGameSet`, `GameLogInitialized`, `GameLogClosed` and `GameBonusPaid`. `MarketView` gains `gameSlots` and `sprintRegs`. * **A close of a position on a fee-terms slot carries the market's `FeeTermsTable`.** Pass the position's slot: `feeTermsTableFor(market, config, 'settle', feeTermsSlot(position.flags))`. Without it the program refuses the close (6239). * **`MAX_POSITION_SLOTS` is 21** (was 12). The new `DEFAULT_POSITION_SLOTS` (12) is the size of a new book. If you pass `MAX_POSITION_SLOTS` as the size of a create or a grow, pass `DEFAULT_POSITION_SLOTS`. * `settleComputeUnitLimit(shape)` returns the limit of a dearer `settle` shape; `computeUnitLimit('settle')` (47,000) is unchanged. * `errorForCode` knows the venue's codes 6378 to 6392; `minuteErrorForCode` knows Minute's 6053 to 6057. **Do:** install 0.8.0 to open Sprint rounds. If you size books with `MAX_POSITION_SLOTS`, change that first. **0.7.0** 2026-11-22 **Impact for a client: update before you open or add on the upgraded program.** The program upgrade this version ships with changes the account list and the transaction shape of a kind-2 or kind-3 `open` and `add_collateral`. An older SDK's commit is refused, usually with 6350 or 6265. No USDC moves; a transaction that lands still pays its network fee. A breaking change also applies if you import a removed oracle-quote name (see Removed). * **Commits.** A kind-3 `open` or `add` carries the `GovTable`, the Instructions sysvar and the writable `CapitalState`; a kind-2 one carries the sysvar and the writable `CapitalState`. An `open` also carries the fee-terms table when it reads one. Before the commit, a transaction may hold only Compute Budget instructions and at most one each of `init_trader_account`, `set_referral`, `bind_referral` and Minute's `init_player`. Put any guard instruction after the commit. One commit per transaction. * **Session approvals** name the `TradeDelegate` account, not the session key. An approval made earlier keeps trading until it expires, at most 7 days after the upgrade. A renew moves it. * **Compute-unit limits**, each measured on the release program, on its most expensive shape, plus the usual 15 % margin: | instruction | 0.6.0 | 0.7.0 | | - | - | - | | `open` | 26,000 | 22,000 | | `add_collateral` | 26,000 | 19,000 | | `void_open` | 23,000 | 18,000 | | `reverse_add` | 23,000 | 20,000 | | `stamp_book` | 16,000 | 11,000 | | `set_take_profit` | 13,000 | 15,000 | | Minute `open_round` / `double_down` / `settle_round` | 73,000 / 74,000 / 72,000 | 72,000 / 73,000 / 71,000 | `settle` (47,000) is unchanged. * `computeUnitLimit(name, { quotePost })`: `quotePost` has no effect. Remove it when convenient. * **Removed:** `QUOTE_POST_CU`; from the sender, `submitQuoted`, `composeQuotedTransaction`, `wireGates`, `WireContext`, `SubmitArgs`, `QUOTED_LAYOUT`, `QuotePostShape`, `postedQuoteView`, `assertQuotePostIsSendable`, `quoteFromPostPayload`; `SWITCHBOARD_EXPO`, `SB_MAX_SIGNATURES`, `SB_MESSAGE_BYTES`, `SB_SUFFIX_FIXED`, `SWITCHBOARD_QUEUE`, `SWITCHBOARD_QUOTE_PROGRAM`, `switchboardQuoteAddress`; and the field of `AssetFeeds` that held the quote feed. * `marketParamsFor` throws for the removed quote-feed option. **Do:** install 0.7.0 when the program upgrade is live. If you import a removed name, delete that code path. **0.6.0** 2026-11-10 **Impact for a client: required on a market of feed kind 3.** On 0.5.1, `priceAccountsFor(market, config, 'open')` throws on such a market, and `ix.requestClose` without its third argument builds a request the program refuses (`GovTableRequired`). Read `market.feedKind[0]` (or `isKind3Market(market)`) on every request: a market's kind can change. * `priceAccountsFor(market, config, 'open' | 'add_collateral')` returns the governance table on a feed-kind-3 market, with the market's fee-terms account after it on an open that needs it. On a kind-2 market every list is the same as in 0.5.1. A kind-3 `'settle'` or `'set_take_profit'` is the keepers' and needs the market's tick accounts as a new, optional fourth argument. * New: `requestCloseFor(market, accounts, seq)` builds `request_close` with the governance table on a feed-kind-3 market, and `requestCloseGovTableFor(market)` is that third argument of `ix.requestClose` (`null` on kind 2). * New: `addCollateralFor(market, config, accounts, args)` builds an add on either kind. `addCollateralForMode` is for kind 2 only and now refuses a kind-3 list instead of dropping the table. * New export: `lazerCommitRemaining`, the list a kind-3 open, add or close request carries (the governance table). * Minute: `minuteIx.openRound` and `minuteIx.doubleDown` take `priceAccountsFor(market, config, 'open')` and `priceAccountsFor(market, config, 'add_collateral')` on a feed-kind-3 market; `pricingRemainingAccounts` still throws there. **Do:** install 0.6.0. Build an open with `priceAccountsFor`, an add with `addCollateralFor` and a close request with `requestCloseFor`. **0.5.1** 2026-10-28 **Impact for a client: none.** The package exports the same names as 0.5.0. * `settlementIdentity(market)` returns the label `'benchmark'` for a market whose price feed is of kind 2. * The shipped IDL and `program-constants.json` carry no key of the config authority. Read `config.authority` from the chain. * Its `engines` field says Node 20.10 or later. A fresh install loads on Node 20.19 or later and on Node 22.12 or later, and does not load on Node 20.18, 21 or 22.0 to 22.11. `@solana/web3.js` (`^1.98.0`) is its one peer dependency. **Do:** install 0.5.1. **0.5.0** 2026-10-28 **The first version on npm.** * ESM only. The package ships compiled modules (`dist/*.js`), their type declarations and the program's IDL (`dist/idl.json`). * It decodes the venue's accounts and events, prices a position as the program does, reports every gate that can refuse an action before you send it, and builds the instructions. * `settlementIdentity(market)` returns a different label for a market whose price feed is of kind 2. **Do:** install 0.5.1. # Data API Source: https://docs.rekt.money/data-api The read-only HTTP API for settled trades and ended positions: which routes answer the last 48 hours, which keep the whole history, the page size, the request limit, and what a 429 means. `https://data.rekt.trading` serves settled trades and ended positions, rebuilt by replaying each settlement through the same engine the program runs. It is read-only and it needs no account. A web page on any origin can call it: responses carry `Access-Control-Allow-Origin: *`, and a preflight (`OPTIONS`) is answered. It sets no cookies and accepts no credentials. Start at `GET /v0/health`. The program is the ground of truth and this API is a lagging mirror of it. It answers no live question. Read live state from the chain through the [SDK](/sdk/quickstart). ## Routes | Route | Returns | History | | - | - | - | | `GET /v0/health` | how fresh the archive is, and the limits that apply to your requests | now | | `GET /v0/stats` | counts by market and by day, and the daily notional volume series | all time | | `GET /v0/markets` | notional volume by market | all time | | `GET /v0/trades` | settled trades, newest first. Filters: `owner`, `market`, `beforeSlot`, `limit`, `format=ndjson` | last 48 hours | | `GET /v0/trades/{signature}` | one settled trade | last 48 hours | | `GET /v0/minute/rounds` | Minute rounds, newest open first. Filters: `owner`, `sinceSlot` and `beforeSlot` (the slot the round opened in), `limit` | last 48 hours | | `GET /v0/duel/rounds` | Duel rounds, newest first: each entry and how Knockout settled it. Filters: `owner`, `matchup`, `status`, `sinceSlot` and `beforeSlot` (the slot of the round's first entry), `limit` | last 48 hours | | `GET /v0/positions` | positions that have ended, settled or returned, with the phase each reached; a position that is still open is read from the chain. Filters: `owner`, `market`, `phase`, `signature`, `beforeSlot`, `limit` | last 48 hours | | `GET /v0/capital` | the queue of unpaid wins in totals, how long the oldest has waited, and the closes made when a market had no price, by day | all time | | `GET /v0/referral` | referral totals: the USDC referrers have claimed, how many referrers were paid, and how many traders are linked. Totals only | all time | `owner` takes a wallet as base58 or as 64 hex characters. Any other value matches nothing: the page is empty and `filters.owner` repeats what you sent. ## Duel rounds A Duel round is one matchup and one start time (`matchup`, `anchorS`). Each entry in `entries` is a position on Knockout: Knockout prices it, settles it and pays it, and the entry shows that settle. * `side`: `long` when the entry is on the top coin of the matchup, `short` when it is on the bottom coin. * `payout` is what Knockout paid to the Player's winnings account. `net` is `payout` minus `stake`. `result` is `profit`, `loss`, `even`, or `voided` when Knockout returned the entry. * `swept` is the sweep of the winnings to the wallet, when it is in the settle transaction. * `streak` is the streak credit of the wallet for the round, with the bonus it credited and, in `bonusPaid`, the payment of that bonus. `streakEnded` is the end of the streak at the round, with the reason. * `outcome` is the price move of the round from its bell settles: `up` when the top coin gained on the bottom coin. * With `owner`, each round holds only the entries of that wallet. `owner` also takes the wallet's Player account. `sides`, `outcome` and `payout` stay those of the round. ## Volume is notional Every volume figure on this API is **notional**, in the field `notional`: for each settled trade, the collateral the position settled with (the stake, with any adds) times its leverage tier, summed. It is in base units of USDC (6 decimals), as a decimal string. A settlement whose tier cannot be recovered from its money is not in `notional`; `notionalUnknown` counts those. `/v0/stats` and `/v0/markets` state the same definition in `volumeNote`. ## Limits * **Per-transaction history is the last 48 hours.** `/v0/trades`, `/v0/minute/rounds`, `/v0/duel/rounds` and `/v0/positions` return rows settled or ended in the last 48 hours. A Minute round that is still open is dated by when it opened, and a Duel round that is still live by its start. A page that asks for older rows is empty. `/v0/trades/{signature}` answers `404` for a trade older than that, the same answer as for a signature it does not hold. `totalMatching`, `matched` and `nextBeforeSlot` count only the rows inside the window. The response states the window in its `window` field. * **Pages hold at most 100 rows**, plus the rest of the last row's slot: a page never splits a slot, so paging with `beforeSlot` set to the previous page's `nextBeforeSlot` returns every row once. A larger `limit` is read as 100. * **Requests are rate-limited.** `GET /v0/health` states the limit under `access`. A request over it gets `429` and a `Retry-After` header with the number of seconds to wait. Wait that long, then retry. * **Days with fewer than 3 settlements are merged into the day after them** in `byDay`, `volumeByDay` and the day series of `/v0/capital`, and the response says so in `dayCells`. A merged day takes the label of the day it joined, and nothing is lost: the cells still sum to the total. * **Poll the aggregates no more than once every 10 seconds.** `/v0/stats`, `/v0/markets`, `/v0/capital` and `/v0/referral` change at most that often and carry `Cache-Control: public, max-age=10, stale-while-revalidate=30`. The per-transaction routes carry `max-age=5`. * **A request URL is at most 2,048 characters.** A longer one gets `414`. `GET /v0/health` returns these figures for the caller that asked, under `access`. Read the limits from there instead of copying them. ## History longer than 48 hours * **Totals and trends:** `/v0/stats` returns `byDay` (settlements per day) and `volumeByDay` (per day: settlements and notional). `/v0/markets` returns the all-time settlements and notional per market. Both cover the whole archive. * **One trader's older trades, or one older trade:** read them from the chain. `readTradeHistory` in the [SDK](/sdk/reference) scans a trader's closed trades from the program's own events. ## A request that is refused | Status | Meaning | What to do | | - | - | - | | `400` | the request used a filter this API refuses | remove it. The filters are the ones in the table above. A parameter this API does not know is ignored | | `400` | the path or the signature is malformed, or `phase` names an unknown or open phase | fix the request. Read an open position from the chain | | `404` | no settled trade with this signature in the last 48 hours, or no such route | read it from the chain, or use the aggregates above | | `405` | a method other than `GET`, `HEAD` or `OPTIONS` | use `GET` | | `414` | the request URL is longer than 2,048 characters | shorten it | | `429` | too many requests | wait `Retry-After` seconds | | `500` | the server failed to answer | retry later | # Glossary Source: https://docs.rekt.money/glossary The words these docs use for Knockout and its SDK, each in one or two sentences, with a link to the page that has the rules. Each term has one meaning on every page. The links go to the page that has the full rules. ## The basics | Term | Meaning | | - | - | | **Knockout** | The product, and what happens when the price hits your barrier: the position ends and the stake is gone. | | **Stake** | What you put into a position, from $0.20 to $1,000. It is the most you can lose. | | **Long, short** | Long gains when the price goes up. Short gains when it goes down. | | **1000x** | Every position is 1000x its stake, on every market. It sets how close the barrier and the take profit are. | | **Take profit** | The target: when the price reaches it, the position closes with a gain. | | **Cash out** | Closing your own position before it hits the barrier or the take profit. | ## Positions | Term | Meaning | | - | - | | **Barrier** | The level at which a position is knocked out and you get nothing back. It is a distance from the entry, and the 1000x sets that distance. See [the barrier](/venue#the-barrier). | | **Target** | The take-profit level: a multiple of the stake, at or above 2.00x and up to `config.params.payoutCapMultiple`. A position with no target of its own has the payout cap as its target. | | **Rung** | The target as the program reads it: `rung_bps`, in basis points of the stake. `20_000` is 2.00x, the lowest target. | | **Tenor** | The protocol's own clock for a position, `config.params.tMaxSeconds`, frozen onto the position at open. It is the indefinite value, so a position has no protocol clock. See [the tenor](/how-it-works#the-tenor). | | **Book** | Your trader account: one account that holds all your positions. `init_trader_account` creates it, with 1 to 21 position slots (12 by default). `open` does not create it. | | **Slot (book)** | A place for one position in a book. Slots are reused, so a slot index is not a handle. | | **Slot (time)** | A Solana slot. Every wait on the venue is a count of slots. | | **`seq`** | The sequence number of a position, and its handle. Every later instruction addresses a position by its `seq`. | ## Orders and closes | Term | Meaning | | - | - | | **Commit** | An `open` or an `add_collateral` that lands. The stake is taken in that transaction and the order waits for its fill. Events give its slot as `commitSlot`. | | **Fill** | The step that writes the entry price of an order: the first price of the venue's price feed at or after the order's target slot. See [orders and closes](/sdk/orders#opening-an-order-then-a-fill). | | **Filler** | A key on the venue's list that sends the fill. You cannot fill your own order (`NotAListedFiller`). | | **Returned order (void)** | An order that is not filled. The whole stake comes back (`OpenVoided`). After `d + T_fill` slots anyone may send `void_open`, and the venue's keepers do. A returned order is a normal outcome. | | **Close request** | `request_close`, signed by the owner or a session key. It carries no price and cannot be withdrawn. A settle completes it. | | **Stamp** | `stamp_book` records on the book that a price touched a level. The settle that pays it follows. | | **Window quote** | The first price of the venue's price feed at or after the start of the current exit window, `exitTarget + K × W`. A settle of a requested or marked exit needs it. | | **Keeper** | A program that sends settles, stamps and returns of orders. Anyone may send these. The venue runs keepers, and nobody is paid for sending a close. | ## Timing settings Each one is a governed count of slots. Read them through the SDK on each request. See [the timing settings](/sdk/orders#the-timing-settings). | Term | Meaning | | - | - | | **`d`** | The delay from an order, an add, a close request or an expiry mark to its target slot. | | **`T_q`** | The latest slot after the target at which the first price can still fill an order or an add. | | **`T_fill`** | The slots after the target in which a filler can fill. After them, anyone can return the order. | | **`W`** | The exit window: the slots in which one price prices a requested or marked exit. | | **`W_ko`** | How old a price can be and still prove a knockout or a take-profit. | | **`M_add`** | The slots after a filled double-down's price in which the position is held. | ## Units | Term | Meaning | | - | - | | **Base units** | Money in the SDK is a `bigint` in USDC base units, six decimals. `1_000_000n` is one dollar. | | **Basis point** | One hundredth of one percent. Rates such as `exitFeeBps` are in basis points. | | **Micro-basis-point** | One millionth of a basis point. `barrierMicroBp` and `takeProfitMicroBp` are distances from the entry in this unit. See [units](/sdk/reference). | # How the product works Source: https://docs.rekt.money/how-it-works Direction, stake, barrier and take profit, and the ways a position ends. Your position's **terms** (its fees, barrier, take profit and tenor) are locked in when it opens. A later change by the protocol never reaches a position you already hold. Two guardian switches can stop it closing; see [settlement](#settlement-is-permissionless). The one thing you can change is its **size**: you can add to a live position. That averages your entry and moves both price levels with it. See [adding to a position](#adding-to-a-position). **The governed timing settings are read when each step runs:** the minimum hold, the grace before a no-price close and the slot delays. A position that stored a funding grace of `0` also reads the live `config.params.borrowGraceS` (see [funding](#funding)). ## An open is an order **Your stake is taken when the open lands, and the venue's next price sets your entry.** The open carries no price. The program records it as an **order** with a target slot a short, governed delay after the slot in which it landed (`d` slots). The entry is the first price of the venue's price feed at or after that target. A filler on the venue's list writes it, and the order becomes a position. The barrier and the target are distances from that entry. * **The price on your screen when you tap is not your entry.** Your entry is the next price after the delay. * **An order that is not filled in time is returned.** If the first price comes too late or does not meet the venue's quality rule, if the market closes, or if no filler lands inside the fill window, anyone can return the order, and the venue's keepers do. You get your whole stake back. * **You cannot fill your own order.** Only a filler on the venue's list can write an entry. * **A landed open is not yet a position.** Read your entry when the order is filled, never from the screen at the tap. The timing settings, the events that report each step and the SDK calls are in [orders and closes](/sdk/orders). ## The five choices **1. Asset and direction** Which market you are trading, and whether you are long or short. The market names the price feed that decides your outcome — see [the price that decides](#the-price-that-decides-your-outcome). **2. Stake** Your collateral, between the venue's `minCollateral` and `maxCollateral`. It, and any entry fee paid on it, is the entire amount at risk. The bounds are governed and live on chain; read them from the config account. **3. Target (optional)** A take-profit target you can add, as a multiple of the stake. Any multiple **at or above 2.00x** is admitted, up to the protocol's payout cap — the one ceiling, read as `config.params.payoutCapMultiple`. Without one, the target is the payout cap. **4. 1000x** How far the price has to move to reach either end, so how *fast* the position ends. **1000x on every market.** Pass `tier` on `open`: `0` means the market's own. A market's `tier` is the ceiling and the venue's `config.minTier` is the floor. Above the ceiling is refused (`LeverageAboveMarketTier`), below the floor is refused (`LeverageBelowMinTier`), and so is a value the program does not list. Both values are governed: read them from the chain. The 1000x sets the DISTANCE to both levels. The fee terms read the size of the price move, so the same target pays differently at another tier. **5. Timer (optional)** You may set your own expiry. Leave it at zero and you have no clock at all, because the protocol's tenor is indefinite (see [the tenor](#the-tenor)). A timer you set is at least 26 seconds. **Setting a timer is free.** A timed open pre-pays nothing. See [the fees](#the-fees). ## The barrier Every position has a **barrier**: a price, fixed at open, a set distance on the losing side of your entry. If the price touches it, the position is knocked out and **you get nothing back**. Three things to know: * **It is a distance, not a dollar amount.** The distance is set by the position's 1000x tier and its loss tax rate, both locked in at open. At 1000x the barrier is near, which is why a position ends fast. * **It is direction-relative.** For a long it sits below entry; for a short, above. * **It is fixed at your open.** Its distance is frozen when your order lands, and its price is set when the order is filled. A governance change later does not move a barrier that already exists. The exact distance for the terms you are about to open is returned by the SDK's `openPreview().barrierMicroBp`, and the resulting price by `levels()`. Read it, show it to the person taking the risk, and do not hand-compute it. > [!WARNING] > > **At the barrier the trader receives nothing.** Any interface that tells a user they keep some > fraction of their stake on a knockout is wrong. Plan your product around the stake being gone. > > Nothing is meant literally, not "nothing worth rounding". At the barrier the loss tax takes the > whole of the position's equity, and the crumb the flooring leaves behind — a few base units, a > ten-thousandth of a cent — goes to the liquidity pool, not back to the trader. `settlePreview` returns > `0` for a knockout and that zero is exact. ## The target The target is optional. It is the other side of the barrier: a price, also fixed at open, sitting the distance away that corresponds to your chosen multiple. Touch it and the position has a gross gain of the multiple less one, times your stake: a 2.00x target is a gain equal to the stake. What you receive is that gain less the share of it the terms withhold and less the exit fee, so a target pays less than its multiple. [Fees and limits](/limits#how-a-win-is-calculated) has a worked example. A target can be **any multiple of your stake at or above 2.00x**. The floor is `RUNG_FLOOR_BPS`, 2.00x. **Without a target, the position's target is the payout cap**, the one ceiling, `config.params.payoutCapMultiple`; a market carries no take-profit ceiling of its own. A value above the live cap is refused `RungAbovePayoutCap`. ## Adding to a position **A trader may add collateral to a position that is already live.** It is one order, not two: the stake grows, the entry becomes the average of the prices actually paid, and both levels move with it. **An add is an order too.** It takes the added stake when it lands (`CollateralCommitted`) and carries no price. The add is priced at the first price of the venue's price feed at or after the same short delay, and then one of two things happens: * **It is filled** (`CollateralAdded`): the entry becomes the blend, and both levels move with it. * **It is returned** (`AddReversed`), in full: if no price or no filler comes in time, or if at the add's price the position is already at its barrier or its target. A returned add keeps the time it added to your timer. Until the add is filled or returned, and for a short, governed time after a filled add's price (`M_add` slots), you cannot close the position, move its target or add again (`AddPending`). In that time a price from before the add that breached the old barrier still proves a knockout: the position is knocked out on its old stake, and the added stake comes back. A touch of the target while an add waits for its price does not count, and it is lost if the add is then filled. > [!WARNING] > > **Adding while you are AHEAD moves the barrier TOWARD the live price.** This is the single fact > an interface must not bury. The 1000x is fixed by the POSITION's tier, chosen at open and frozen into the slot, so an add buys *size at > market*. It is not "adding margin": it adds size at the same 1000x. > > Both levels are distances from the entry, and the entry always moves toward the price the add > filled at. So for a long: > > | You are | The entry | The barrier price | The take-profit price | > | - | - | - | - | > | **behind** (price below entry) | falls | falls — **away** from the price | falls — toward the price | > | **flat** | unchanged | unchanged | unchanged | > | **ahead** (price above entry) | rises | rises — **toward** the price | rises — away from the price | > > A short is the mirror in price and the identical statement in distance. **A trader who is ahead > spends their profit cushion on size.** Do not offer this control to a winning position with > copy that suggests it protects one. Adding neither realises nor creates a profit or a loss. A trader who is $0.40 down and adds $1 is still \$0.40 down at the add's price: the entry is the collateral-weighted **harmonic** mean of the old entry and the fill price, which is the only blend with that property, and it is also the average cost basis every trading interface already shows. ```text theme={"dark"} E' = C' × E0 × S / (C0 × S + dC × E0) ``` What else it does, all of which a client has to handle: * **The add is fee-inclusive, exactly as an open is.** You hand `added_budget` — the total to add — the venue takes its entry fee from inside it, and the debit is at most that. `min_added_collateral_out` is the trader's mandatory floor on the increment SIZE, the signature over what the add buys. * **The stake bounds bind on two different quantities.** The minimum binds on the *increment*, the maximum on the *total*. So a position already holding more than `maxCollateral − minCollateral` has **no legal add at all** — quote the admissible range and never render a control whose every value is refused. * **The clock may only be lengthened.** `extend_timer_s` is a delta in seconds and it only ever goes forward, and never past the tenor frozen on the position. A double-down is the only way to move a position's own timer, and it cannot shorten it. * **A position that has touched a level cannot be added to.** An add whose price is at or through the barrier, or at or through the take-profit, is returned in full (`AddReversed`). * **The hold clock restarts.** A filled add re-prices the position, so [the minimum hold](#the-minimum-hold) before a close you ask for runs again from the add's price. Funding, below, is the one clock an add does **not** reset: it is measured from the original open. ```ts theme={"dark"} import { addCollateralForMode } from '@rekt-trading/1000x'; // The account list is `open`'s: an add grows a slot, it creates none. // `config` is the decoded config. The add carries no remaining accounts, and while adds are off // this refuses to build it (`AddsDisabled`). export const addIx = addCollateralForMode( config, { authority, trader_token: traderToken, config, market, vault, vault_token: vaultToken, protocol_token: protocolToken, positions, delegate: null, }, { seq, // the handle, never the slot index // Read the live entry fee. At an entry fee of 0 the increment equals the budget. added_budget: 250_000n, // the fee-inclusive TOTAL to add; the debit is AT MOST this extend_timer_s: 0, // a DELTA, forward only. 0 leaves the clock alone min_added_collateral_out: 250_000n, // mandatory floor on the increment SIZE; 0n refused (MinCollateralOutRequired) }, feeds, ); ``` ### Sizing an add from a total The trader can name what leaves their wallet instead of naming the increment. `sizeAddForTotal` is that inverse, and it is **not** `sizeForTotal` with a different argument. ```ts theme={"dark"} import { admissibleAdd, sizeAddForTotal, toEnginePosition } from '@rekt-trading/1000x'; // `admissibleAdd` takes the ENGINE position, so a decoded slot goes through `toEnginePosition`. const room = admissibleAdd(toEnginePosition(position), config.params); // null = the position is full const size = sizeAddForTotal(500_000n, config.params.entryFeeBps, room!, /* setsTimer */ false); // size.collateral 500000n the increment this budget buys — pass as `min_added_collateral_out` // size.debit 500000n what actually leaves the wallet (at most the budget you sign) // size.dust 0n what could not be spent // size.summary "$0.50 adds $0.50 and costs exactly $0.50." // size.refusal null or a Gate-shaped refusal naming the bound that was missed ``` Two things differ from the open path's answer, and each is money: * **`setsTimer` does not change the debit.** Setting a timer is free, on an open or an extension. * **The bounds are `admissibleAdd`'s interval, not `config.params`.** The ceiling binds on the total, so what a position may still take is the governed ceiling less what it already holds. `size.debit` is never above the total, so the number the trader typed is the `added_budget` you sign and the chain debits at most that. A fee change landing between the quote and the signature can only shrink the increment, and the `min_added_collateral_out` floor you set from `size.collateral` turns that into a `BudgetBelowCollateralFloor` revert rather than a silent shrink. > [!NOTE] > > `addPreview`, `admissibleAdd`, `addCollateral` and `addImpact` answer *"what would this add do"* > and *"what increments are legal"*, which covers the blended entry, the admissible range and the > barrier's new price. Quote with them; do not derive the blend by hand from the formula above, and > do not offer the control without showing where the barrier moves to. `addGates` is the gate report > for an add — see [reading gates](/sdk/gates). ## The tenor **The tenor is the protocol's own clock for a position. It is `config.params.tMaxSeconds`, a governed parameter, and it is frozen onto your position at open.** The tenor is the indefinite value, so a position has no protocol clock: it ends by its barrier, its target, your own close, your own timer if you set one, the close of its session on a market with trading hours, or the no-price close under [How a position ends](#how-a-position-ends). A position keeps the tenor it froze at open. The SDK tests for it with `isIndefiniteTenor()`; show "no limit", not a date. A position that froze a finite tenor is closable by anyone when the tenor runs out. **On a market with trading hours, the tenor is shorter.** It is `config.params.tMaxSeconds` or the time left until `market.sessionBufferS` before the session's close, whichever is shorter, so the position ends before its session closes. No live market has trading hours; see [markets](/markets#what-happens-in-each-gold-session). The freeze is a rule of the program: settlement reads the tenor stamped on your position, so a governance change afterwards cannot change a position you already hold. **Read the live value rather than typing it, and do not build an interface that promises a reader a duration from a constant.** You may also set a shorter timer of your own. The two clocks are independent, and the earlier one is the moment your position first becomes closable by a stranger. A double-down can push your own timer out, never in — see [adding to a position](#adding-to-a-position). The SDK computes both from the position itself: ```ts theme={"dark"} import { deadlines, isIndefiniteTenor, type PositionView } from '@rekt-trading/1000x'; export function clocks(position: PositionView) { const d = deadlines(position); const noTenor = isIndefiniteTenor(position.tMaxSeconds); return { openedAt: d.openedAt, // The protocol's clock, read from the position's own frozen tenor — never from live config. // null means no limit: show "no limit", never a date. tenorExpiresAt: noTenor ? null : d.tenorExpiresAt, // Your own timer, or null when you set none. userExpiresAt: d.userExpiresAt, // The earlier of the two: when a stranger may first close this position. firstExpiryAt: noTenor ? d.userExpiresAt : d.firstExpiryAt, }; } ``` ## How a position ends > [accordion] Knockout — the price touched the barrier > > The position is over and the trader gets nothing back. Plan for it: at 1000x the barrier sits > close enough to entry that an ordinary move reaches it. A knockout settles *at* > the barrier no matter how far past it the price ran, so it needs no exit price to price it. > > Anyone may prove it with any signed price that is newer than the entry and at most `W_ko` > slots old, a governed setting. So a position can be knocked out by a recent price that has > already moved back on your screen. After a close request or an expiry mark, only a price that is > not later than the exit price can knock the position out. > [accordion] Take-profit — the price reached your rung > > The position closes at its target, with a gross gain of the multiple less one, times your stake. > You receive that gain less the share the terms withhold and less the exit fee, within the payout > cap. It is proved the same way as a knockout, and the price that proves it must also clear [the minimum > hold](#the-minimum-hold). A touch while a double-down waits for its price does not count. After > you move your target, only a price at least `d` slots later proves the new one. > [accordion] Expiry — a clock ran out > > Either your own timer or the protocol's finite tenor (an indefinite tenor never expires). From the deadline, anyone may mark the expiry > (`mark_expiry`). The position settles at the first price at or after `d` slots from the mark, > by the same window rule as a close you ask for, whatever that price is: a position expiring in > profit is paid, and one expiring in loss is settled where it stands. > [accordion] Voluntary — you closed it > > You ask for the close with `request_close`, signed by you or by a session key you authorised. > The request carries no price, so it cannot fail on a stale one, and **it cannot be withdrawn**. > The exit price is the first price of the venue's price feed at or after `d` slots from the > request. Anyone may then send the settle that pays it, and the venue's keepers do. > > **The window rule.** If nobody settles inside the exit window (`W` slots) from that target, the > price becomes the first price of the next window, and so on, and a knockout price in between > still counts. So the close price is not locked when you ask, and no interface should say it > is. You cannot ask inside [the minimum hold](#the-minimum-hold). > [accordion] Last resort — no price could be obtained > > If no price can be obtained for a long time, a position can be closed with no quote, only while no fresh price exists. > > A live position is paid its stake back with the exit fee waived; a position already stamped at a > level is paid that level, and a target level pays the exit fee. The close is refused while the oracle is frozen, on an order that is > not filled, and while an add waits for its price. > > **A position that is not settled before its session's close ends at par,** on a market with trading > hours: a quote from a later session never prices it. The SDK names seven close reasons, because expiry has two flavours: `voluntary`, `knockout`, `takeProfit`, `userExpiry`, `tenorExpiry`, `lastResort` and `borrowSpent`. The last is a close that funding makes possible once it has used a position up; it cannot arise while the funding rate is 0. ## The minimum hold **A position cannot be closed by its owner in the first slots after its entry price.** The venue has one hold for every market, `resolveMinHoldSlots(config.minHoldSlots)` slots, and a market can have a longer one, `market.closeHoldSlots`. The longer of the two applies. Both are governed settings: read them from the chain. * The hold starts at your entry price, and again at the price of each double-down. * A close request inside it is refused (`MinimumHoldNotMet`, `MarketHoldNotMet`). The position is not affected. Send the request again from the first slot the hold allows: `closableFromSlotOf(position, config, market)` gives that slot from three public accounts, so an app can show "can close in N seconds" with no guess. * A take-profit must also clear the hold, measured to the slot of the price that proves it. The venue's hold also applies to the end of your own timer. * A knockout is never held back, and a market's own hold never holds back a timer end. ## Settlement is permissionless Every close ends with a `settle` that **anyone may send**. Only one step needs the owner: the request for a voluntary close. A knockout and a take-profit are proved by the price, and the two expiries and `lastResort` by the clock. Every priced close carries a signed quote from the venue's price feed; `lastResort` needs none. Two switches can stop closes: the guardian's oracle freeze starves every priced close of a price and refuses `lastResort`, and its settle kill-switch refuses every close. Only the config authority lifts either. Read `config.oracleFrozen` and `config.settlesDisabled`. **Nobody is paid for sending a close.** The protocol pays its submitter nothing — no fee, no share of the settlement, no gas rebate. If you run a keeper, budget for it as a cost. ```ts theme={"dark"} import { isPermissionless, type CloseReasonName } from '@rekt-trading/1000x'; // Everything except `voluntary` can be submitted by a stranger, and `voluntary` too once the owner // has requested it: pass the position's phase, `isPermissionless('voluntary', 'ExitRequested')`. // None of them pays the submitter for it. export const permissionless: CloseReasonName[] = ( ['voluntary', 'knockout', 'takeProfit', 'userExpiry', 'tenorExpiry', 'lastResort', 'borrowSpent'] as CloseReasonName[] ).filter((r) => isPermissionless(r)); ``` ## The payout cap **No target can be set above the payout cap.** The cap is the governed `payoutCapMultiple`, the largest multiple the program lets a target take. A position with no target of its own has the cap as its target. Read it rather than typing it. **A win is paid in full. Part of it may be paid later, in order. There is no guaranteed time. The amount queued ahead of you is shown.** How, and what a client shows, is in [how a win is paid](/liquidity#how-a-win-is-paid). ## The fees Four, all on chain. Three are charged on an event; funding is charged on time. Setting a timer is free. The rates, with the date they were read, are on [Fees and limits](/limits). * an **entry fee** (`config.params.entryFeeBps`, basis points of the stake), taken from inside your budget when you open, and from the increment when you add. It is 0, so an open costs the stake and nothing more. The venue is fee-inclusive: you hand a total, it takes the fee from within it, and the debit is at most the number you signed; * a **loss tax**, charged at a close at a loss and taken from the position's equity before the exit fee. It is a share of the loss (`config.params.lossTaxBps`), frozen onto the position at open. [Fees and limits](/limits#how-a-loss-is-calculated) has the rate, the steps and a worked example; * an **exit fee**, charged at every close **except a knockout**, and waived on a live position closed by `lastResort`. It is a share of the exit value, the money the position closes with before the fee. The rate depends on the price move at the close: one rate when the close is a gain beyond a small band around the entry price, a higher rate when it is a loss beyond the band, and a rate between the two inside the band. On a gain, the terms also withhold part of the gain: the share you keep is smaller for a small move and rises with the size of the move. [Fees and limits](/limits#how-a-win-is-calculated) has the values, dated, and a worked example. A position freezes its terms when it opens, so a later change to a market's terms never reaches a position that is already open. The terms of a market are read from its fee-terms account (`feeTermsTablePda` in the SDK), and the share of each close is on its `SettlementFeeTerms` event. A wallet linked to a referrer pays less exit fee ([Referrals](/referrals)); * **funding**, a rate on the time held. The rate is 0: nothing is charged for holding. A knockout pays no exit fee. The total that leaves your wallet is **at most the budget you hand the venue** — it takes its entry fee from inside it, and setting a timer is free, so nothing is added on top. The SDK sizes the position for you: ```ts theme={"dark"} import { sizeForTotal, parseUsdc, type ConfigView } from '@rekt-trading/1000x'; // Money is bigint in USDC base units. Parse text exactly; never through a float. const budget = parseUsdc('1.00'); // The venue is fee-inclusive: it takes its entry fee from INSIDE the budget and opens the largest // position the remainder buys, so the debit is AT MOST what you hand it. Setting a timer is free, // so a timed open costs no more. // Read `config.params` from the config account in production. export function open(config: ConfigView) { const size = sizeForTotal(budget, config.params); // size.debit is at most the budget; size.collateral is the position it buys (the smaller number), // which you also sign as `min_collateral_out`. return { debit: size.debit, collateral: size.collateral }; } ``` ### Funding The funding rate is 0, so nothing is charged for holding a position. It is a governed field, and a position freezes the rate it opens with. Funding is charged out of the payout at settlement, after the loss tax and the exit fee, never out of your equity, so it does not move the price that ends your position. All of it goes to the pool. Its fields are named `borrow` in the program and the SDK (`borrowRateBpsPerHour`, `borrowGraceS`). A position freezes its rate when it opens, and a stored grace of `0` reads the live `config.params.borrowGraceS`. [Fees and limits](/limits) has the rate in force; read the position's own `borrowRateBpsPerHour` to price its settlement. > [!NOTE] > > Every one of these parameters is **governed**: they can be changed on chain by the protocol's > authority. Do not cache them. Read them from the config account, and show the reader how old > your copy is. ## The price that decides your outcome It is the price feed of the market you traded, not "the price of SOL" on some other screen. Every venue reports a slightly different number. Every price is a signed update from the market's price feed, and the program checks the signature before it uses it. * **Your entry** is the first price at or after your order's target slot. An order is filled only by a price that meets the venue's quality rule for an entry. Otherwise it is returned. * **Your exit** is the first price at or after your close's target slot, by the window rule, or the price that proves a level. * If no quote can be obtained at all, `lastResort` is the backstop. Markets can also close. BTC, ETH, SOL, XRP and HYPE trade around the clock. A scheduled event (a rate decision, a print) can also close a market to new opens for a window, and a market can be paused or halted. See [markets](/markets) for the rules at each close. The SDK models this as a state, never a boolean. Branch on the state: ```ts theme={"dark"} import { type MarketAvailability } from '@rekt-trading/1000x'; export function describe(a: MarketAvailability): string { switch (a.state) { case 'open': return 'open for business'; case 'closed': return `closed (${a.reason}), opens ${a.opensAt.toISOString()}`; case 'closing-soon': return `opens already refused; forced close at ${a.forceCloseAt.toISOString()}`; case 'halted': return `halted: ${a.reason}`; } } ``` ## Your positions live in one account A trader has a single account holding several position slots — twelve by default in the SDK, and a client may ask for anywhere from 1 to 21 when the account is created, or resize it later. That account is created by its own instruction, not by opening a position — but account creation and your first open **fit in one transaction**, so a first-time trader signs once and pays the account's rent only on that first trade. The rent comes back to whoever paid it when the account is closed. That transaction is one an interface composes; the SDK's own composer will not build it for you. [Opening a position](/sdk/opening#create-and-trade-in-one-transaction) has the recipe. Slots are reused, so a slot index is not a position handle. The SDK gives you `{ trader, slot, seq }` and settlement addresses positions by `seq`, so a stale handle finds nothing instead of closing a neighbour. See [reading positions](/sdk/positions). # Knockout Source: https://docs.rekt.money/index Go long or short at 1000x on Solana. Pick a direction and a stake. Your stake is the most you can lose. Rekt runs two products on Solana: **Knockout**, described on this page, and **[Minute](/minute/how-to-think-about-it)**, a timed round built on Knockout that you cannot close early. **[Sprint](/minute/sprint)** is Minute's 20-second round, live on SOL, BTC and ETH. **Knockout lets you go long or short at 1000x, with two simple limits.** A **barrier**: if the price hits it, the position is knocked out. And a **cap** on the most a position can pay. You pick a direction and a stake, and the rules are fixed the moment you open. If you have gone long or short on other crypto venues, the shape is familiar. The difference is the end: no margin calls and nothing to top up. If the price hits your barrier, the position closes and your stake is gone. That is the most you can lose. Holding a position is free: the funding rate is 0. > [card] [How the product works](/how-it-works) > > Direction, stake, barrier, tenor — and the ways a position ends. > [card] [The venue](/venue) > > What the program does: admission and the queue, the pricing path, the bounds on loss and payout. > [card] [Fees and limits](/limits) > > What a trade costs, the stake limits, the hours, the minimum hold and how a win is paid. Dated, > and they can change. > [card] [Build on it](/sdk/quickstart) > > A bot that quotes, opens and closes in one file. The SDK reads state, predicts every refusal > before you send, and prices every close. > [card] [Orders and closes](/sdk/orders) > > An open is an order that the venue's next price fills, and a close is a request anyone > completes. The rules a client or a bot builds against. > [card] [The liquidity pool](/liquidity) > > One shared pool takes the other side of every position and funds every win. How a win is paid, how > the pool is read, and how it loses money. > [card] [Markets](/markets) > > BTC, ETH, SOL, XRP and HYPE, around the clock. ## Where it is running | | | | - | - | | **The program** | `1oooxLtzLiYV6LcDybrEPcyXVLPWGnAmeif9s5oNrp6` on Solana mainnet. **This is the ground of truth.** Derive every account address from it rather than copying one | | **The facts API** | `https://data.rekt.trading` — settled trades, rebuilt by replaying each settlement through the same engine the program runs. No account; a web page on any origin can call it. Per-transaction routes answer the last 48 hours and all-time totals stay on `/v0/stats` and `/v0/markets`; see [Data API](/data-api). Start at `/v0/health` | > [!WARNING] > > **The facts API is a lagging mirror and answers no live question.** There is no RPC endpoint in > that process. Pool size, open positions, the current price, whether a trade would be admitted — > none of those routes exist. Read live state from the chain through the SDK; read history from the > API. Every response carries `asOf` and says `stale: true` when the archive has stopped advancing. ## A trade, in short * **Pick a market and a direction.** BTC, ETH, SOL, XRP or HYPE, long or short. All five trade around the clock. See [markets](/markets). * **Pick a stake** from **$0.20 to $1,000**. Every position is **1000x** your stake. * **Add a take profit if you like**, at **2.00x** your stake or more. Without one, the target is the payout cap. * **Your entry is the next price.** The stake is taken when your open lands, and the next price after a short delay sets your entry. If no price comes in time, your whole stake comes back. * **It ends one of three ways:** knocked out at the barrier, closed at your take profit, or cashed out by you. You can also set a timer. There is no other clock. * **Opening is free.** You pay when you close: a loss tax and a higher exit fee on a loss, a lower exit fee on a win, and the terms keep part of a gain (less of a big one). The numbers are on [Fees and limits](/limits). | The choice | What it does | | - | - | | **Market** | Which price decides your outcome: BTC, ETH, SOL, XRP or HYPE; see [markets](/markets). | | **Direction** | Long or short. | | **Stake** | What you put in, from $0.20 to $1,000. It is the most you can lose. | | **Take profit (optional)** | Any multiple of your stake from 2.00x up to the payout cap. Without one, the target is the payout cap. Reaching it is a gross gain of the multiple less one, times the stake, before the exit fee and the share of the gain the terms keep ([how a win is calculated](/limits#how-a-win-is-calculated)). | | **1000x** | The same on every market. It sets how far the price has to move to hit your barrier or your take profit, so how fast the position ends. | ## How a win is paid Opening a position takes your stake and nothing else. If the pool cannot cover a new position when it fills, the order is returned with your whole stake and no fee. **A win is paid in full. Part of it may be paid later, in order. There is no guaranteed time. The amount queued ahead of you is shown.** When you cash out, your stake comes back at once and the profit is paid from the pool's free cash. Whatever the pool cannot pay yet joins a queue and is paid first in, first out. [How a win is paid](/liquidity#how-a-win-is-paid) has the rule in full. > [!NOTE] > > The program never writes down an amount it owes: it is paid in full or stays owed. A payout that > cannot be delivered is held for its trader, and it is released to the pool if nobody claims it > within `config.params.unclaimedPayoutExpiryS` > ([the liquidity pool](/liquidity#an-expired-unclaimed-payout-is-released-to-the-pool)). ## Know this before you trade * **The barrier is close, on purpose.** At 1000x a small, ordinary move can knock you out. That is the product working. Size every trade as if that is a normal result. * **At the barrier you get nothing back.** The position is over and the stake is gone. * **Doubling down does not protect you.** You can add to a live position. It averages your entry, so adding while you are **ahead** moves your barrier closer to the price. See [adding to a position](/how-it-works#adding-to-a-position). * **Your stake is the most you can lose.** There is nothing to top up and no way to owe more. Read [the venue](/venue) before you trade. The [risk disclosure](/risk) follows it. ## Who takes the other side One shared pool takes the other side of every position. It pays every win and keeps a share of the fees. The pool belongs to the protocol: nobody can deposit into it or withdraw from it. See [the liquidity pool](/liquidity). ## Everything is on chain Every fee, limit and delay lives in accounts you can read yourself. The protocol can change them, on chain and in public, and a position keeps the terms it opened with. The SDK reads the live values: ```ts theme={"dark"} import { Connection } from '@solana/web3.js'; import { configPda, decodeConfig } from '@rekt-trading/1000x'; // SOLANA_RPC_URL is read from the environment. Never hardcode an endpoint that carries a token. const connection = new Connection(process.env['SOLANA_RPC_URL'] ?? '', 'confirmed'); const info = await connection.getAccountInfo(configPda().address, 'confirmed'); const config = decodeConfig(new Uint8Array(info!.data)); // The live bounds, the live entry fee and funding rate, the live cap — read, not typed. // The exit fee is in the market's fee-terms account (`feeTermsTablePda`), not in the config. console.log(config.params.minCollateral, config.params.maxCollateral); console.log(config.params.entryFeeBps, config.params.borrowRateBpsPerHour); console.log(config.params.payoutCapMultiple, config.params.tMaxSeconds); ``` > [!WARNING] > > Knockout is early software. It has not been audited by a third party. Trade only with money you > can afford to lose entirely. [Read the risk disclosure](/risk). # Fees and limits Source: https://docs.rekt.money/limits What a trade costs and what you can do: the fees, how a win and a loss are worked out, the stake limits and the minimum hold. *Values as of 2026-11-23; they can change.* Every value here lives on chain. A change is public, and a position keeps the terms it opened with. Read the live value through the SDK before you trade. ## What a trade costs | | | | - | - | | **Open** | Free. The entry fee is 0, so the stake is the whole cost of an open. | | **Add collateral** | Free. The entry fee is 0 on the added amount too. | | **Close** | On a loss, a **loss tax** first: 42.85 % of the loss, taken before the exit fee. Then an exit fee, charged on the **exit value**: the money the position closes with, before the fee. The base terms are **5 %** on a win and **12 %** on a loss, and a close within 1 bp of your entry price pays a rate between the two. The terms a new position freezes can be lower than the base terms: read them before you open (see [the terms in force](#the-terms-a-position-freezes)). On a gain the terms also withhold part of the gain: you keep 63 % of it at a move of 1 bp or less, and the share you keep rises with the size of the move, to 87 % at 10 bp and 93 % at 100 bp or more. [How a win is calculated](#how-a-win-is-calculated) and [how a loss is calculated](#how-a-loss-is-calculated) have the steps and a worked example each. | | **Knockout** | No fee. The stake is gone and nothing is left to charge. | | **No-price close** | If no price can be obtained for 24 hours, a live position gets its stake back with no exit fee. | | **An order that is returned** | The whole stake comes back. No fee. | | **Holding** | The funding rate is 0. It is a governed rate, and a position keeps the rate it opened with. | Setting your own timer is free. A wallet linked to a referrer pays less exit fee: 10 % less for a link made from 2026-11-10, and 25 % less for a link made before. See [Referrals](/referrals). ### The terms a position freezes Each market's fee terms are entries in its fee-terms account (`feeTermsTablePda(market)`), and the market names the entry a new position freezes. That entry can be lower than the base terms on this page. Read it before you open: `openFeeTerms(config, market, table)` returns the terms an open would freeze. A position keeps the terms it froze until it closes, and its close shows the rate it paid on its `SettlementFeeTerms` event. ## What you can do | | | | - | - | | **Stake** | From $0.20 to $1,000 for one position. A $1,000 stake is a $1,000,000 position at 1000x. | | **1000x** | The same on every market. It sets how far the price has to move before a position ends. | | **Barrier** | Every position has one, set when it opens. If the price touches it, the position is knocked out and you get nothing back. At 1000x it is close to the entry price. The SDK returns the exact distance for the terms you are about to open: `openPreview().barrierMicroBp`. | | **Target (optional)** | A take-profit target you can add: at least 2.00x your stake. Without one, the target is the payout cap. Reaching the target means a gross gain of the multiple less one, times your stake: a 2.00x target is a gain equal to the stake. You receive that gain less the share the terms withhold and less the exit fee. The payout cap is 65,535x, the largest value the program accepts, so the pool's cover decides whether a position fits, not a cap on the target. | | **Timer** | Optional. A timer you set is at least the venue's timer floor: 26 seconds by default, a governed setting that can be from 10 to 26 seconds. | | **Minimum hold** | You cannot ask to close in the first 6 slots after your entry price, about 1.3 seconds at mainnet's measured slot time. A knockout is never held back. | | **Side cap** | Each side of a market can be capped at a share of the pool. It is off today. When a side is full, a new position on that side is voided at its fill and the whole stake comes back (6395). | ## How a win is calculated When you close, the math runs in four steps. Each step uses the terms your position locked in when it opened. 1. **Gross gain.** The move in your favour, times your exposure. At 1000x, a move of 10 bp (0.10 %) is a gross gain equal to your stake. 2. **The part you keep.** The terms withhold part of a gain. The share you keep rises with the size of the move (table below). A flat close or a loss has no gain to withhold from. 3. **The exit value.** Your stake plus the part of the gain you keep. 4. **The exit fee.** A share of the exit value: 5 % on a win at the base terms. What is left is paid to you. The share of the gain you keep, by the move in your favour: | Move | Share you keep | | - | - | | 1 bp or less | 63 % | | 2 bp | 71.5 % | | 5 bp | 81.5 % | | 10 bp (a 2.00x target at 1000x) | 87 % | | 100 bp or more | 93 % | Between two moves in the table the share is on the straight line between them. **Worked example, at the base terms.** A \$1.00 stake at 1000x with a 2.00x target. The price moves 10 bp in your favour and reaches the target. | Step | Amount | | - | - | | Gross gain (the target) | \$1.0000 | | Part you keep, 87 % | \$0.8700 | | Exit value, stake plus the part you keep | \$1.8700 | | Exit fee, 5 % of the exit value | \$0.0935 | | **Paid to you** | **\$1.7765** | At the base terms, a 2.00x target on a $1.00 stake therefore pays $1.7765, not \$2.00: the multiple names the gross payout, before the exit fee and the share of the gain the terms withhold. `openPreview().maxPayout` is that gross figure. Read what a close paid from its `SettlementFeeTerms` event. ## How a loss is calculated A close at a loss pays the loss tax first, then the exit fee (at the base terms, 12 % of the exit value at a move of 1 bp or more against you). At 1000x, a move of 2 bp against you is a loss of 20 % of your stake. **Worked example, at the base terms.** A \$1.00 stake at 1000x. The price moves 2 bp against you and you close. | Step | Amount | | - | - | | Loss | \$0.2000 | | Equity, stake less the loss | \$0.8000 | | Loss tax, 42.85 % of the loss | \$0.0857 | | Exit value, equity less the loss tax | \$0.7143 | | Exit fee, 12 % of the exit value | \$0.0857 | | **Paid to you** | **\$0.6286** | A move against you that uses up the whole stake is the barrier: the position is knocked out and you get nothing back. ## How a win is paid **A win is paid in full. Part of it may be paid later, in order. There is no guaranteed time. The amount queued ahead of you is shown.** Your stake comes back at once; what the pool cannot pay yet joins a first-in, first-out queue. The rule in full is under [how a win is paid](/liquidity#how-a-win-is-paid). ## Trading hours | Market | Hours (UTC) | | - | - | | BTC, ETH, SOL, XRP, HYPE | Always open. | Gold (XAU/USD) is not available for now. See [markets](/markets). For the mechanics behind each value, read [how the product works](/how-it-works) and [the venue](/venue). The SDK page [reading the venue](/sdk/reading#where-each-value-is-read) lists where each value is read. # The liquidity pool Source: https://docs.rekt.money/liquidity One shared pool takes the other side of every position and funds every win. How a win is paid, how the pool is read and how the pool loses money. There is one shared pool. It takes the other side of every position on every market, funds every win, and receives a share of the fees traders pay. The pool belongs to the protocol. > [!WARNING] > > **The pool's losses are real and they are not theoretical.** The pool funds every winning > position out of its own assets. A run of trader wins draws it down. Nothing about the design > prevents that. A win larger than the pool can pay at once is paid in order, from a queue: see > [how a win is paid](#how-a-win-is-paid). > [!NOTE] > > **The program has no instruction to deposit into the pool and none to redeem from it.** ## The numbers that describe the pool Read them together. Either one alone will mislead you. | Gauge | What it means | | - | - | | `lpAssets` | The pool's assets: the vault's token balance less any payout already settled and owed to a named trader, and nothing else. It does **not** subtract what the queue still owes: subtract the unfunded queue and the parked amount before you read it as free money. | | `withdrawable` | The SDK's name for `lpAssets` less every stake the pool holds (`vault.totalReserved`). Nobody can withdraw from the pool, so it is not an amount anyone can take out. It does **not** subtract the unfunded queue or the parked amount, so it is not the cash a fill can use. | | `fOpen` | The free cash a fill is admitted against, from `capitalGauges`: the token balance less the payouts owed to named traders, less every stake, less the unfunded queue and the parked amount. It is 0 while any amount is parked or the cash cannot fund the whole unfunded queue. The cover rule and the capacity floors decide what a fill can take. | `vaultGauges` also returns `openable`, `pendingRedemptionValue` and `sharePriceMicro`. They describe deposits and redemptions, which the program does not offer, so do not show them. ```ts theme={"dark"} import { capitalGauges, capitalPda, cashInputs, decodeCapitalState, decodeVault, vaultGauges, vaultPda, } from '@rekt-trading/1000x'; import { Connection } from '@solana/web3.js'; // `vaultTokenBalance` is the balance of the SPL account that `vault.tokenAccount` names: read it, do not guess. export async function poolGauges(connection: Connection, vaultTokenBalance: bigint) { const [vaultInfo, capitalInfo] = await Promise.all([ connection.getAccountInfo(vaultPda().address, 'confirmed'), connection.getAccountInfo(capitalPda().address, 'confirmed'), ]); if (!vaultInfo || !capitalInfo) throw new Error('a pool account does not exist'); const vault = decodeVault(new Uint8Array(vaultInfo.data)); const capital = decodeCapitalState(new Uint8Array(capitalInfo.data)); return { pool: vaultGauges(vault, vaultTokenBalance), // lpAssets, withdrawable cash: capitalGauges(capital, cashInputs(vault, capital, vaultTokenBalance)), // fOpen, queued, parked }; } ``` ## How a win is paid **A win is paid in full. Part of it may be paid later, in order. There is no guaranteed time. The amount queued ahead of you is shown.** * **Opening takes the stake and nothing else.** The venue decides at the fill whether a position fits, against a rule the program applies per market and in total. An order that does not fit is returned with the whole stake and no fee. A hedge, a smaller target and a close are never refused by it. * **At a close the stake comes back at once.** The profit is paid from the pool's free cash when no earlier claim is unfunded; whatever is left joins the queue. The settlement events say how much was paid now and how much was queued. * **The queue is first in, first out, and cash that other positions leave in the pool funds it.** The protocol's own share of a close is paid last, and not at all while any claim is unfunded. * **Anyone can deliver funded money** with `pay_queue`, in line order, to the wallet recorded on the account. Money for an account that cannot receive it is held for that account under the unclaimed rule below. * **When the line is nearly full, a second unpaid win of the same account waits behind its first.** * **A book with an unpaid entry cannot close its account** until it is paid. A client shows what happened and where the account stands, never a forecast: at a close, the amount paid now and the amount queued; while queued, the amount ahead, the entries ahead, what has been funded, what has been delivered and the entry's age. It does not show an estimate of a wait. ## Wind-down The operator can wind the venue down. Positions still end by their own rules. An order or an add sent during a wind-down is taken but never filled: it is returned, and the whole stake comes back. A target raise is refused. ## How the pool loses money * **Traders win.** The pool pays. Over a run of favourable outcomes for traders, the pool's assets fall, and they may not come back. * **Capacity is limited.** A run of large wins can draw the pool down, and what it cannot pay at once is paid from the queue. * **Nothing will catch the pool.** There is no insurance fund standing behind the pool, no backstop, no protocol treasury commitment and no third party standing behind a balance. See [the insurance fund](#the-insurance-fund). * **Parameters are governed.** Fees, bounds and caps can be changed on chain by the protocol's authority. Every change is public and readable. * **This software has not been audited by a third party.** ## What reaches the pool Five things reach the pool, and they are not the same kind of income: * **What losing positions lose, and the part of a gain the terms withhold.** The loss of a losing position stays in the pool, and so does the part of each gain that the terms withhold. * **A share of the exit fee.** Opens are free. Traders pay an exit fee on most closes (not on one paid at the barrier). The exit fee is a share of the exit value, higher on a loss than on a win; the rates are on [Fees and limits](/limits). * **A share of what losing positions forfeit.** The loss tax is divided between the pool and the protocol. * **Funding, in full.** Its rate is 0, so it collects nothing: [Fees and limits](/limits) has the rate. * **An unclaimed payout that expires.** See below. What that adds up to depends on how much is traded, at what sizes, against a pool of what size — read it from the on-chain accounts the SDK exposes, live, rather than from a number on this page. ### An expired unclaimed payout is released to the pool When a settlement cannot deliver a payout — the trader closed or froze their USDC account — the money is escrowed inside the vault and held against that trader's name. It sits **outside** `lpAssets` for the whole of that time, so it is not part of the pool's assets. If nobody claims it before `config.params.unclaimedPayoutExpiryS` has passed, anyone may sweep it, and the sweep releases the claim rather than moving any tokens. The money was already in the vault; dropping the obligation raises `lpAssets` by exactly that amount. ## The insurance fund There is no insurance fund standing behind the pool, and no rule obliges the protocol to cover the pool's loss. A win is paid from the pool's assets and from nothing else. ## Before you rely on the pool > [card] [Read the risk disclosure](/risk) > > The complete list of what can go wrong, for the pool and for traders, in plain language. # Markets Source: https://docs.rekt.money/markets The live markets, BTC, ETH, SOL, XRP and HYPE, their hours, and the four states a market can be in. **Live: BTC, ETH, SOL, XRP and HYPE.** All five trade around the clock. Gold (XAU/USD) is not available for now. Each market carries its own calendar on chain (`market.sessions`), so read a market's state rather than assume it is open. > [!NOTE] > > This page gives the rules. For the states as a type, and the fields on them, see > [how it works](/how-it-works#the-price-that-decides-your-outcome) and [reading > gates](/sdk/gates). ## The markets | Market | Hours (UTC) | Size | | - | - | - | | BTC | Always open | 1000x | | ETH | Always open | 1000x | | SOL | Always open | 1000x | | XRP | Always open | 1000x | | HYPE | Always open | 1000x | Minute rounds run on BTC, ETH, SOL and XRP (`market.minuteEnabled` is true). [Sprint](/minute/sprint) rounds run on SOL, BTC and ETH. Only the markets in the table are open to trade. A paused market refuses new opens and adds with `MarketPaused`, and closes keep working. ## Markets with trading hours > [!NOTE] > > No live market has trading hours. Gold (XAU/USD) follows the rules below, and it is not available > for now. ## When gold trades Gold trades in five sessions each week. Each session opens at 23:00 UTC and closes at 21:00 UTC on the next day. | Session opens (UTC) | Session closes (UTC) | | - | - | | Sunday 23:00 | Monday 21:00 | | Monday 23:00 | Tuesday 21:00 | | Tuesday 23:00 | Wednesday 21:00 | | Wednesday 23:00 | Thursday 21:00 | | Thursday 23:00 | Friday 21:00 | Gold is closed from 21:00 to 23:00 UTC on Monday to Thursday, and from Friday 21:00 UTC to Sunday 23:00 UTC. **The hours are fixed in UTC.** They do not move when clocks change for daylight saving. A scheduled event window can halt a market for a few minutes. Windows are entries on the market's account (`market.eventWindows`), so read them there. While a window lasts, opens and adds are refused and the market reads **halted**. ## What happens in each gold session | Time (UTC) | Opens | Adds | Positions | | - | - | - | - | | 23:00 to 20:25 | Accepted | Accepted, see rule 3 | A new position's life ends at 20:30 at the latest. | | After 20:25, to 20:30 | Refused, `SessionEndsBeforeTenor` | Accepted on a live position, see rule 3 | Live until 20:30. | | 20:30 to 21:00 | Refused, `SessionEndsBeforeTenor` | Refused | Every position's life has ended. Anybody may mark its end, and it is closed at the next price. | | At 21:00 | Refused, `MarketClosed` | Refused | The session closes. A position that is not settled before the close ends at par. | | 21:00 to 23:00 | Refused, `MarketClosed` | Refused | No new gold position opens. A quote signed after the close never prices a position from the session before. | The rules behind that table: 1. **Every gold position ends by 20:30 UTC on the day its session closes.** Its life is the protocol tenor (`config.params.tMaxSeconds`) or the time left until 30 minutes before the close, whichever is shorter. The 30 minutes is `market.sessionBufferS`. The life is frozen onto the position at open; `deadlines(position).tenorExpiresAt` reads it. 2. **Opens stop 35 minutes before the close.** A new position must get at least five minutes of life, so from 20:25 UTC an open is refused with `SessionEndsBeforeTenor` and the market reports **closing soon**. Open again after 23:00 UTC. 3. **Adds follow the position, not the clock.** You can add to a live gold position until its own life ends: the venue judges an add against the position's remaining life, not against the whole frozen tenor. An add that would outlive the session is not filled: it is returned in full, with cause 6. The SDK's add gate refuses such an add before you send it. 4. **From 20:30, a gold position is closed at the market price.** When its life has ended, anybody may mark its end (`mark_expiry`), and it is closed at the first price after a short delay from the mark (`tenorExpiry`). It is paid what it is worth, gain or loss. 5. **A position that is not settled before its session's close ends at par.** A quote signed after the close never prices a position from the session before. Such a position is closed with no quote (`lastResort`): a live position gets its stake back with no exit fee. A position already stamped at a level is paid that level, and a target level pays the exit fee. This close is refused while the oracle is frozen. See [the no-price close](/sdk/settling#the-no-price-close). **The workaround for rule 2:** read the state before you build a transaction. `availability()` reports **closing soon** together with `forceCloseAt`, the time at which positions on that market end. Poll it, or read the market's calendar directly. ## Holidays, early closes and pauses **The calendar is the regular weekly schedule. It has no holidays.** For a holiday or an early close, the venue can pause gold for that session. **The venue can also pause gold at other times.** While gold is paused, opens and adds are refused with `MarketPaused`, and closes continue. Read `market.paused`, or the market's state, and do not assume that the weekly schedule holds on every date. ## The four states A market is always in exactly one of four states. Branch on the state, not on a single `isOpen` boolean. | State | What it means | | - | - | | **Open** | Opens, adds and closes all proceed normally. | | **Closing soon** | The session is open, but **opens are refused**. Adds to a live position are accepted until its life ends, at `forceCloseAt`. | | **Closed** | The session is closed. Opens and adds are refused. A market that is always open never enters this state. | | **Halted** | A separate stop: a scheduled event window, a pause, or a feed that has stopped answering during an open session. It does not mean the session is closed. | ## Where to go next > [card] [Reading gates](/sdk/gates) > > Every refusal a market with trading hours can raise, before you send. > [card] [Error handling](/sdk/errors) > > The refusals by name and code, and whether retrying can ever help. > [card] [Opening a position](/sdk/opening) > > The transaction shape, and where an availability check belongs in it. > [card] [How it works](/how-it-works) > > The product mechanics this page assumes. # What a Minute round does Source: https://docs.rekt.money/minute/how-to-think-about-it What a Minute round does: no early exit, the bounds on loss, time and payout, the fees on opening, doubling down, and how a round closes. ## No early exit Once a round is open, there is no exit until the clock runs out, the barrier is hit, or the take-profit is reached. No instruction in the program lets a player end their own round early. The one thing a player can still do is commit more; see [doubling down](#doubling-down-extends-the-clock). A round opens as an order on the venue. The stake is taken when the order lands, and the venue's next price after a short delay sets the entry. If no price comes in time, the order is voided and the whole stake is returned. ## What is bounded > [card] Loss is bounded > > The most a player can lose is what they committed. There is no margin call and nothing to top up. > [card] Time is bounded > > The deadline is set when the round opens, from Minute's config. Only the player's double-downs move it. A finite position tenor is a further limit on it; under the indefinite tenor the round's own deadline is the only one. > [card] Payout is bounded > > The round's target is set from Minute's config when the round opens. A win is paid in full: the stake comes back at once, and part of the profit may be paid later, in order, with no guaranteed time. The amount queued ahead is shown. What is not bounded is how much a player ends up committing if they keep doubling down. Each add is its own order at its own moment. The ceiling is the venue's collateral cap per position, plus Minute's limit on adds when its config sets one. ## Fees on opening Two fees can apply when a round opens, and both come out of what the player commits: Minute's, and the venue's on what is left after Minute's. Both are proportional to the commit. There is no flat charge. Each double-down pays the same two fees: Minute's at the rate frozen when the round opened, and the venue's at its live rate. The live rates are read from the market and config accounts, not from this page. Both entry fees are 0: see [Fees and limits](/limits). The amount that leaves the wallet is the amount committed, to the base unit, because every fee is taken from inside it. The position is smaller than the commit by the fees on opening. Minute takes no fee when a round closes: its own exit fee is 0. The venue's exit fee is taken from the round's exit value. **On SOL, BTC, ETH and HYPE a round has Minute's own fee terms**, the market's classic Minute slot: | Term | Value | | - | - | | Exit fee on a win | 2.5 % of the exit value | | Exit fee on a loss | 12 % of the exit value | | A close at the entry price | no exit fee; the fee rises with the size of the move to the full rate | | Share of a gain kept | 53.55 % at a move of 1 bp or less, 60.77 % at 2 bp, 69.27 % at 5 bp, 73.95 % at 10 bp and 79.05 % at 100 bp or more, on the straight line between those moves | On a market with no classic slot, a round pays the same terms as a Knockout position on that market ([Fees and limits](/limits)). A round's payout is therefore less than the gross payout at its target, before the exit fee and the share of the gain the terms withhold. Those terms are frozen when the round opens, so a later change never reaches a round that is already open. Read them from the market's fee-terms account, not from this page: `openFeeTerms(config, market, table, {})` returns the terms a classic round would freeze (`classicCurSlot(market)` names the classic slot; 0 means the market's ordinary terms). What a close paid is on its `SettlementFeeTerms` event. A classic open carries the fee-terms account writable (`minuteIx.open_round` adds it); without it the round freezes the market's ordinary terms. ## Doubling down extends the clock A double-down adds to a live round. Each add pushes the deadline out by the round's extension, frozen at open. An add is refused in the last seconds before the deadline (the round's add margin, frozen at open) and when the extension would pass a finite position tenor. A round that is doubled down can run considerably longer than its first clock. The terms of a round are frozen at open, so an add cannot change the rules. It changes the size. A double-down is priced the same way as the open: at the venue's next price after a short delay. If no price comes in time, or the pool has no room to cover it, the add is reversed: the whole added stake is returned, and the time it added stays on the clock. Every double-down equals the opening stake, and a round's total stays within the venue's maximum position. Until it is priced, a second double-down waits. ## The close A round also ends when the barrier is hit or the take-profit is reached, at the venue's price. When the clock expires, the round becomes closable, and after the deadline anyone may send the close. The player does not have to be present. The close is priced by the venue's price feed: the first price after a short delay from the moment the end of the round is marked. If nobody closes it inside the exit window, the next window's price applies. If no price can be obtained for a long time, the no-price close (`lastResort`) applies. A guardian stop (`config.settlesDisabled` or `config.oracleFrozen`) blocks the close until it is lifted. See [risks](/risk#if-you-trade). A second close cannot pay twice and cannot pay anyone else. The first close moves the round out of live, and any later attempt finds no live round and reverts. The terms were frozen at open and the price is the venue's, so at any slot exactly one price can settle the round and the closer does not choose it. ## Where rounds are offered A round opens only on a market where Minute is enabled (`market.minuteEnabled`): BTC, ETH, SOL and XRP. See [Markets](/markets). ## What a round does not do * It does not close early at the player's request. * It does not limit the loss below the whole commit. * It does not fix the entry at the price on the player's screen. # Integrating Minute Source: https://docs.rekt.money/minute/integrating The typed dependency, the governed dials, the fee model, who pays, who settles, the per-market gate, and the transaction a round needs. **Minute to Win It** is a separate on-chain program that wraps this venue. A player commits a stake, a sixty-second clock starts, and the round ends when the clock runs out, the barrier is hit or the take-profit is reached. Minute opens a real position here through CPI, handing the venue a fee-inclusive `budget`. Program: `MinXAXaPZezFMc8mm1uZnK8NcYt7Fhbr7Eifdnw7cfH` · Config PDA: `3WQ7QsWJJhqa1REGjUJFzCUNPSonbaXKcZoJbDwQnYq4` ## Decode with the SDK. Do not transcribe the layouts. The SDK decodes Minute's accounts and events, so no layout needs to be copied into your repository: ```ts theme={"dark"} import { decodeMinuteConfig, decodePlayerAccount, decodeMinuteEvent, minuteConfigPda, } from '@rekt-trading/1000x'; ``` A decoder turns a layout change into a compile error or a refused read, where a transcribed offset drifts silently. If you decode bytes off the wire instead (an indexer has no choice: the bytes *are* the interface), use `decodeMinuteEvent` and the event decoders next to it rather than deriving your own. > [!WARNING] > > **On `RoundOpened`, `gross_stake − stake` is Minute's fee plus the venue's.** `stake` is the > collateral the *venue* resolved. Minute's own fee is `floor(gross_stake × entry_fee_bps / 10_000)`, > from the event alone; subtract it from the difference to get the venue's cut. > `RoundExtended.added_collateral` is the **measured** position delta, not the amount the player > typed. ## Read the governed dials from the chain. Every time. `min_stake`, `max_stake`, `entry_fee_bps`, `exit_fee_bps` and `initial_timer_s` are **governed**. They move by a transaction, with no release on your side and no warning. > [!WARNING] > > An integrator who copies today's rate into their own config ships a display that is wrong the day > it moves — **and every test passes**, because their number and their display agree with each other > perfectly. Self-consistency is the failure mode, not the defence. Read them with `decodeMinuteConfig(bytes)` from the account at `minuteConfigPda()`, and prefer failing closed when the config is unreadable over falling back to a remembered value. ## The fee model: fee-inclusive, top to bottom Both layers take their fee from INSIDE the number handed to them, and neither adds anything on top. **The number the player types is the number that leaves the wallet.** The two money instructions: ```rust theme={"dark"} open_round(game_kind: u8, direction: u8, total_in: u64, min_collateral_out: u64) double_down(seq: u64, expected_add_count: u16, added_total_in: u64, min_added_collateral_out: u64) ``` `total_in` / `added_total_in` is the fee-inclusive total — **the exact number that leaves the wallet**, and what `min_stake` / `max_stake` bound. `min_collateral_out` / `min_added_collateral_out` is a **floor on the resolved position**: forwarded to the venue and re-checked by Minute against what the venue actually minted, so a venue fee that moves between your quote and execution **reverts** instead of quietly buying less. **`0` is refused by name** (`MinCollateralOutRequired`: 6050 in Minute's table, 6168 in the venue's) — it is the absence of a floor, not a floor. The venue's own 6050 (`RungAboveMarketCap`) is reserved and raised by nothing. > [!WARNING] > > **There is no `max_total_debit` argument.** `min_collateral_out` pins what the player GETS, not > what they pay. An add is always exactly the round's opening total: `added_total_in == round.opening_gross`, which is also the open's `RoundOpened.gross_stake`. One field, read off the round or off the event — not a range, and not `round.stake` or `round.opening_stake`, both of which hold the venue-resolved collateral and are refused by name (`AddMustEqualOpeningStake`, 6042 — Minute's code; the venue's 6042 is reserved and never raised). **1. Minute's fee is ABSORBED** `entry_fee_bps` comes **out of** the stake, not on top. A player who commits \$1.00 has exactly \$1.00 leave their wallet toward Minute, of which the fee is a part. Minute never adds to what the player typed. `min_stake` and `max_stake` bound this **gross** figure, so a typed \$0.25 is a legal 250,000 stake — **do not gross down for Minute's fee.** **2. The venue is ALSO fee-inclusive: Minute is a pass-through** The venue takes its own fee from inside the budget it is handed, exactly as Minute does. Minute takes its cut off the top and hands the remainder DOWN to the venue as a `budget`; the venue takes its own `entry_fee_bps` from INSIDE that budget and opens the largest position the remainder buys. **Nothing is added on top at either layer**, and a round's timer costs nothing extra. So the wallet debit **is** the number the player typed: one SPL transfer, of exactly `total_in`, and both fees are paid out of it. > [!NOTE] > > The wallet debit is a single transfer of the typed amount. The fees round the POSITION, which is > why `min_collateral_out` exists. > [!NOTE] > > The venue's entry fee is 0, so the venue takes nothing from the budget it is handed. > > Minute's own entry fee and exit fee are 0 too. A round's close pays the venue's exit fee on the market's classic > Minute slot where the market names one (`MarketView.classicRegs`; SOL, BTC, ETH and HYPE today), and on the terms > of a Knockout position on that market otherwise: see [how a round is paid](/minute/how-to-think-about-it) and > [Fees and limits](/limits). Read both programs' fees from their config accounts and the market's fee-terms account. Here it is as arithmetic. The number you type is the number that leaves the wallet. Only the last line depends on the two entry fees: ``` typed total 250,000 (Minute's min_stake) -> Minute absorbs its entry fee; the remainder goes to the venue as a `budget` -> the venue absorbs its own entry fee from INSIDE that budget and opens what it buys -> TOTAL WALLET DEBIT = 250,000 exactly. Not "at most". -> RESOLVED POSITION = 250,000 <- equal to the typed total at Minute 0 bps + venue 0 bps; smaller whenever either fee is above 0 ``` **A typed \$0.25 total debits \$0.25.** Any fee comes out of it, not on top of it. When a fee is above zero, the POSITION is smaller than the typed number, since both fees are absorbed from inside it. The binding floor is therefore the venue's `min_collateral` on the RESOLVED position, not a grossed-up stake: read it from the chain, and set the CPI's `min_collateral_out` to the collateral you predicted for the budget — never a token value like `1`, which satisfies the check and protects nothing. If you need a specific minimum position, that is a governance question about `min_stake` and `min_collateral`, re-derived whenever the *venue* moves its own fee, which Minute does not control. > [!WARNING] > > **Do not gross the player's input down.** Shrinking the typed number is a silent under-spend: it > opens a smaller round than the player was shown. Send the typed number to `total_in` verbatim, and > read both programs' fees from their config accounts when you predict the position. ### The ceiling is not `max_stake` `max_stake` bounds the **opening** stake. A double-down adds to a live round, so total exposure runs past it. `max_adds = 0` means **uncapped**, not "no adds". The binding constraint is the venue's maximum collateral per position, `config.params.maxCollateral` on the venue's config, and the refusal is **Minute's** `AddExceedsVenueCapacity` (6046). So the ceiling is the venue's number and the error is Minute's; do not look for this code in the venue's table. ## Markets: the venue's per-market gate Minute keeps no market list of its own: `Round.market` may point at any market **the venue has listed**, and an unlisted asset has no `Market` PDA to pass. The venue then applies one gate of its own: a Minute player's book may **open or add** only on a market whose `minuteEnabled` flag is true. Anywhere else the venue refuses with `MinuteDisabled` (6201). Settles are never gated, so a live round is never trapped by it. Offer a round only on a market whose `minuteEnabled` is true and whose `paused` is false (both on `decodeMarket(bytes)`). Only the venue's config authority changes either. Minute is enabled on BTC, ETH, SOL and XRP. ### Markets with trading hours No live market has trading hours. Gold (XAU/USD), which is not available for now, trades in sessions ([markets](/markets#when-gold-trades)). The calendar is on the market (`sessions`, `sessionCount`, `sessionBufferS` on `decodeMarket(bytes)`); read it there, not from this page. On such a market the venue's rules apply to a round exactly as to any position: * **An open is refused outside a session** (`MarketClosed`, 6094) **and near its close**: once less than `sessionBufferS` plus 300 seconds of the session remains (`SessionEndsBeforeTenor`, 6095). The venue shortens the round's position so that it ends `sessionBufferS` before the close. * **A double-down is refused outside a session** (`MarketClosed`); inside one the venue admits it, because the position already ends before the close. Minute refuses one that would carry the clock past the shortened position (`ExtensionExceedsTenor`, 6023, Minute's code). * **A price signed at or after the close cannot settle the round** (`QuoteOutsideSession`, 6295, the venue's code). A round that is still open at the close is closed by the venue's no-price close, `lastResort`, which returns the stake at par once the position's tenor plus the venue's last-resort grace has passed: about a day later. Minute's keeper sends it, and `reconcile_round` then records the round. A round is not left open at the close in the ordinary course: its clock ends well before it. So hide the open button from `sessionBufferS` plus 300 seconds before each close until the session reopens, and show the player when the market reopens. ## Who pays, and who may sponsor Three roles, and they are separate on purpose: | Slot | What it does | Constrained? | | - | - | - | | `payer` | pays lamports | **`init_player` only:** must equal the player | | `player_wallet` | the player's identity | **not a signer** on `open_round` | | `funder` | authorises the USDC | SPL decides — owner **or an approved delegate** | **`open_round` and `double_down` are sponsorable.** Your backend can be `payer`, and a delegate the player approved can be `funder`, so the player never signs the open and never needs SOL. > [!NOTE] > > **A venue session key is not an SPL delegate of the player's USDC**, so it cannot be `funder` on > `open_round` or `double_down`: the session's approval names the player's venue delegate account, > which only the venue program signs for ([session keys](/sdk/sessions#funding-a-game-from-a-session-session_fund)). > To open a round with a venue session and no wallet prompt, send `open_round_session` or > `double_down_session`. They take the same accounts and arguments as `open_round` and `double_down`, > plus `custody_bump` (the canonical bump of the player's custody), with the session key as `funder`. > Three accounts come last, after the venue's own remaining accounts: the owner's `TradeDelegate` > (writable), the venue's governance table and the clock sysvar. The round's instruction calls the > venue's `session_fund`, which moves the stake into the player's custody under the session's window > budget, and then opens the round as `open_round` does. **`init_player` is the exception:** it requires `payer == player_wallet`, and refuses anything else with `PayerMustBeThePlayer` (6038). > [!NOTE] > > **The shape that works:** put a lamport transfer to the player and `init_player` in **one > transaction**, with the player as `payer` and signer. You carry the cost and the player never sees > a fund-your-wallet step. It happens once per player. Rent is a **deposit, not a fee**: it returns to the rent payer when the player's accounts are closed with `close_player`. ## Settlement is permissionless, and a redundant settle is not a no-op Anyone may settle a round's venue position once its clock has expired. If you run your own closer alongside Minute's keeper, that is fine and encouraged — but know the shape of the race: **A second settle of an already-settled position FAILS with the venue's `PositionNotFound` (6057).** It is an error, not a silent success. There is no double-payout and there cannot be, because the state transition gates the money rather than following it — the loser of the race gets a reverted transaction, not a second payout. > [!WARNING] > > Treat `PositionNotFound` on a settle as **success by someone else**, never as an incident. It is the > ordinary case: the venue's own keepers close Minute's positions without invoking Minute at all, and > a `reconcile_round` then records the round. A closer that pages on this pages continuously. ## Error codes are meaningless without their program Anchor numbers **every** program's errors from 6000 — so even 6000 itself collides (Minute's `NotAuthority` vs the venue's `RateOutOfRange`). So: * `6027` is Minute's `RoundNotLive` **and** the venue's `ReserveUnderflow` * `6007` is Minute's `WrongMint` **and** the venue's `NoFreshPrice` > [!WARNING] > > A bare-number match reads a real vault accounting failure as "already settled" and writes a > terminal record while the position is still live. **Key your classification by program**: use the > Anchor error *name* when present, else prove which program refused from the logs — Minute's > failure line present and the venue's absent means the refusal happened before the CPI. `refusalOf(err)` (or `refusalFromLogs(logs)`) does this for you: it names the code by the program that wrote the first `Program failed` line, which is the program that raised it, and gives every reading when there is no log ([errors](/sdk/errors#read-the-code-against-the-program-that-failed)). Take codes from the IDL, never from arithmetic on the enum. A code quoted in prose without its program is a number waiting to be matched on wrongly. ## Round slots: check before you open A player account holds one live round per slot, and classic rounds and Sprint rounds share them. A new account takes the config's `defaultRoundSlots` (4 on mainnet; read the live value from `MinuteConfig`); `resize_player` grows it to at most 8. A full account refuses the open with Minute's `NoFreeRoundSlot` (6017), and the transaction still pays its fee. A round's slot is in use until its settle lands, not when its timer ends or its result is known. Read the account just before you open, and do not open when `free` is 0: ```ts theme={"dark"} import { fetchFreeRoundSlots } from '@rekt-trading/1000x'; const rounds = await fetchFreeRoundSlots(connection, wallet); // { exists, capacity, live, free } ``` `freeRoundSlots(bytes)` does the same from player bytes you have already read. Each live round also holds a position on the player's venue book (`minuteTraderBookFor`); `freePositionSlots(bytes)` reads that book. ## Opening, and the venue's price `open_round` and `double_down` reach the venue's `open` and `add_collateral` by CPI. Those read no price, so neither Minute instruction needs a quote instruction in front of it. The round's venue position is an **order** until a filler writes its entry at the venue's next price after a short delay, and a double-down is priced the same way or returned. A double-down the pool has no room to cover is returned in full, and the round's total stays within the venue's maximum position. Read the entry from the venue's events, not from Minute's: see [events of an order](#events-of-an-order). Minute forwards its remaining accounts to the venue. The SDK's `minuteIx.openRound` and `minuteIx.doubleDown` take them as their last argument and refuse an empty list: ```ts theme={"dark"} import { pricingRemainingAccounts, withFeeTermsTable } from '@rekt-trading/1000x'; // open_round: the sysvar, then the market's fee-terms account when the market has terms. The venue // freezes the terms of the round from it. Without the account the round freezes the legal maximum // as its exit-fee bound and no rung check runs, so always pass it. const openRemaining = withFeeTermsTable(pricingRemainingAccounts(market), market, config, 'open'); // double_down: the venue's add reads no price and no terms. The sysvar satisfies the builder. const addRemaining = pricingRemainingAccounts(market); ``` Never pass `market.feeds`: `feeds[0]` is a feed id, not an account. **On a market of feed kind 2, 3 or 4 the round is a commit, with the venue's commit rules.** * The remaining accounts are the commit list: on feed kind 3 or 4 the governance table, then the Instructions sysvar and the venue's capital account (writable), then, on feed kind 4, the market's terms account (read-only), then the fee-terms account when the market has terms. `priceAccountsFor(market, config, 'open')` builds the kind-2 and kind-3 list. `minuteIx.openRound` and `minuteIx.doubleDown` keep the capital account writable. A round that forwards the capital account read-only is refused (`CapitalRequired`, 6265, the venue's code). * The pool's cover is taken when the round lands, so a round the pool cannot cover is refused at once and nothing moves. * The round's instruction must be a top-level instruction of the transaction, with only Compute Budget instructions and at most one `init_player` (and the venue's first-trade instructions: `init_trader_account`, `set_referral`, `bind_referral`, `mark_minute_trader`) before it. Anything else before it is refused (`LazerCommitShape`, 6350, the venue's code). See [the commit's shape](/sdk/orders#the-commits-transaction-shape-feed-kinds-2-3-and-4). * A session round (`open_round_session`, `double_down_session`) puts its three session accounts after this list. **Closing a round is the venue's `settle` on the player's book, followed by `reconcile_round`.** `settle_round` is refused while the venue runs its liquidity pool (`CapitalRequired`, 6265, the venue's code), because the pool settles every position directly so that part of a win can be queued. A knockout, take-profit or expiry close carries the quote's ed25519 instruction immediately before the venue's `settle`, and `priceAccountsFor(market, config, 'settle')` gives the whole list of remaining accounts. An expiry takes two transactions: anyone marks the venue position's expiry (`mark_expiry`) from the bell, and the settle follows from the mark's `exitTarget` on, with the window quote. See [settling a position](/sdk/settling#request-or-mark-then-settle). Anyone may send the settle, and the venue's keepers do. `reconcile_round` then records the round on Minute's side. If no price can be obtained at all, the venue's no-price close, `lastResort`, applies to the round's venue position directly (see [settling a position](/sdk/settling#the-no-price-close)), and `reconcile_round` then records the round. **Do not gate a close on a pause.** `Market.paused` refuses opens and adds (and a take-profit stamp or retarget), never `settle`. Pause your OPEN button if you must; never your close. ## Events of an order Minute's events are `RoundOpened`, `RoundExtended`, `RoundSettled`, `RoundReconciled`, `Swept`, `PlayerInitialized`, `PlayerResized`, `PlayerClosed`, `ConfigUpdated`, `PauseChanged` and `LookupTableSet`. It has no event named `DoubledDown`. Minute's two round events are emitted when the order or the add lands, before the venue has priced it: * **`RoundOpened.entry_price` is 0** on every open. * **`RoundExtended` is emitted at the add's commit**, also for a double-down that is later returned. Its `entry_price` equals its `entry_price_before`. * **`opened_slot` in both events is the slot of the commit**, not the slot of the entry price. The holds count from the venue's `EntryFilled.quote_slot`, and after a filled double-down from the venue position's `opened_slot` on the book. So do not read an entry, a blend or "the add is done" from either event. The round's entry is the venue's `EntryFilled.entry_price`. The entry after a double-down is the venue's `CollateralAdded.entry_price`, with `entry_price_before`. A returned double-down is the venue's `AddReversed`. Join them to the round on `opener_tag`. ## The transaction is tight A wrapped open names the Minute accounts **and** the venue accounts it reaches, against Solana's 1,232-byte packet limit. Compile a v0 message against two lookup tables. The first is the table Minute's config names (`decodeMinuteConfig(bytes).lookupTable`); read it from the config rather than from your own settings. The second is the venue table for the market, from `chooseMarketTable` (see [session keys](/sdk/sessions#the-byte-wall)). Both are frozen, so cache their contents by address. Measure the signed packet before you send it, and refuse one that does not fit rather than letting the RPC reject it. # Sprint Source: https://docs.rekt.money/minute/sprint Sprint, a short Minute round: the terms, what a player sees, and how to open one with the SDK. **Sprint is a short Minute round, live on mainnet on SOL, BTC and ETH.** A player picks a direction and a ticket in one tap. The round ends at its bell, at the knockout line or at the take-profit. There is no double-down and no early close. | Term | Value | | - | - | | Markets | SOL, BTC, ETH | | Ticket | $1 to $10, in whole cents | | Round length | 20 seconds, from the commit | | Fees | On the exit value: 2.5 % on a win and 12 % on a loss. These are Sprint's own fee terms on that market, frozen when the round opens | | Knockout | None in the first 5 seconds of the round | | Close | the keeper settles it; the payout returns to the wallet | The values change only by a governed write. Read them from `SprintConfig` (below) and the Sprint slot of the market's fee-terms account (`sprintCurSlot(market)`), not from this page. ## The life of a round 1. **Tap.** One `open_sprint` transaction, signed by the wallet, or `open_sprint_session`, signed by a session key. The ticket leaves the wallet when it lands. There is no entry price yet. 2. **Fill.** The venue's next price after a short delay is the entry price. If no price comes in time, the round is voided and the whole ticket returns. 3. **Bell.** At `opened_at + timer_s` the round is marked, and its exit price is the venue's price a short delay later. The result arrives a few seconds after the bell. 4. **Knockout or take-profit.** A price at the knockout line ends the round at a loss of the ticket. There is no knockout on a price from the first 5 seconds of the round (the slot's `noKoS`). A booked knockout is final, even if the price comes back. A price at the take-profit ends it at the capped win. 5. **Money home.** `reconcile_round` moves the payout to the wallet's USDC account. Anyone may send it. A round with no fresh price at its close returns the ticket at par. ## Open one with the SDK ```ts theme={"dark"} import { buildOpenSprint, computeUnitLimit, decodeSprintConfig, sprintConfigPda, } from '@rekt-trading/1000x'; const terms = decodeSprintConfig((await connection.getAccountInfo(sprintConfigPda().address))!.data); if (!terms.opensOn) throw new Error('Sprint is not open'); const open = buildOpenSprint( accounts, // the account list of Minute's open_round: the player, its custody, the venue book, market and vault { direction: 0, total_in: 2_000_000n, min_collateral_out: 2_000_000n }, // long, $2.00; the floor is the ticket market, // decodeMarket of the Knockout market config, // decodeConfig of the venue config ); const limit = computeUnitLimit('open_sprint'); ``` * **Read `SprintConfig` before every open.** `opensOn`, `minStake`, `maxStake` and `timerS` are the live terms. A ticket outside `[minStake, maxStake]` is refused (Minute 6056); a closed Sprint is refused (Minute 6055). * **The ticket is a whole number of cents** (`SPRINT_TICKET_STEP`, 10,000 base units). `buildOpenSprint`, `buildOpenSprintSession` and `buildMinuteInstruction` refuse any other ticket and never round it (`refuseOddSprintTicket`). The program does not check this. If you write the instruction bytes yourself, check it. * **The trailing accounts** come from `sprintTrailingAccounts`: `SprintConfig`, the market's fee-terms table (writable), the game config, the governance table, the Instructions sysvar and the pool's `CapitalState` (writable). The builders append them in this order. * **The session form** (`buildOpenSprintSession`) is funded by a session key. Set `payer` and `funder` to the session key and `player_wallet` to the owner; three more accounts follow, last. * **Compute.** `computeUnitLimit('open_sprint')` and `computeUnitLimit('open_sprint_session')` are the limits to set. A transaction that also carries `resize_player` sets the sum: add `computeUnitLimit('resize_player')`. ## One tap, one transaction * **Make every tap's transaction unique** with a Compute Budget value that differs per tap, for example a counter in the compute-unit price. Two identical taps signed on one blockhash are one transaction, and the network keeps one. * **A retry re-sends the same signed bytes.** If a tap's result is unknown, send the bytes you signed, and keep checking that signature until its blockhash expires. A rebuilt or re-signed transaction is a second trade and takes a second ticket. A new tap stays immediate while another tap's result is unknown. * **Keep each tap's signature.** It links the tap to the `RoundOpened` event in its logs. ## Slots A player account holds one live round per slot. Classic rounds and Sprint rounds share the slots. A new account takes the config's `defaultRoundSlots` (4 on mainnet; read the live value from `MinuteConfig`), and `resize_player` grows it to at most 8: put it **after** the open in the same transaction. A round's slot is in use until its settle lands (for Sprint, the venue `settle` and then `reconcile_round`), not when its timer ends. Check before you send: `fetchFreeRoundSlots(connection, wallet)` returns `{ exists, capacity, live, free }`; do not open when `free` is 0. In front of a Sprint open, a transaction may hold only Compute Budget instructions and at most one each of `init_trader_account`, `set_referral`, `bind_referral` and Minute's `init_player`. A full account refuses the open (Minute 6017). ## The line to show `sprintBreakEvenPrice(input)` walks the program's own payout from the fill's entry price and returns two exit prices. `input` is `{ direction, entryPrice, stake, terms, params, tier, marketTier }`: `params` is the venue config's `params`, `tier` is `SprintConfig.tier` and `marketTier` is the market's tier. | Field | What it is | | - | - | | `profitPrice` | From this price on, up to the take-profit, the program pays more than the ticket. Show this line for a win. | | `breakEvenPrice` | From this price on, the program pays at least the ticket. It can sit on the losing side of the entry. | `sprintPayout(input, exitPrice)` is the program's settlement of one exit price. `terms` is the round's game entry: the market's Sprint slot of its fee-terms table (`sprintCurSlot(market)`), or `feeTermsOfGameArgs` of the game terms. Draw no line before the fill: the entry price is 0 until then. ## Reading results and errors * The close is the keeper's: the venue `settle`, then `reconcile_round`. `settle_round` refuses a Sprint. * A finished round's slot is cleared. Take its kind and result from `RoundOpened` and the settle events, not from the slot. * **Minute and the venue use the same error numbers for different errors.** Read the failing program from the logs (the first `Program … failed` line) before you read the code. The fee-terms table and `CapitalState` must be writable, or the venue refuses (6380, 6265). * A win can be paid partly now and partly later (`SettlementQueued`). # Referrals Source: https://docs.rekt.money/referrals How a referrer registers, how a wallet links itself to a referrer once and for life, the discount a linked wallet gets on the exit fee, the referrer's share and its tiers, how a share is credited and claimed, and what Minute players get. *Values as of 2026-11-23; they can change.* Referrals are built into the Knockout program on Solana. Every rule here is a rule of that program, and every value lives on chain. ## In short | | | | - | - | | **Referrer** | A wallet that registers a referral record. The record collects the referrer's share. | | **Link** | A wallet links itself to one referrer, by its own signature. The link is for life. | | **Discount** | A linked wallet pays **10 %** less exit fee. A link made before 2026-11-10 keeps **25 %**. The rate is fixed into the link when the link is made. | | **Referrer's share** | A part of the protocol's share of each settled trade of a linked wallet. The rate starts at **20 %** and rises in tiers, up to **50 %**. | | **Which trades count** | For the share, only trades committed at or after the moment of the link. For the discount, every close settled after the link exists. | | **Claim** | The record's owner withdraws the credited share in USDC, at any time. | ## Becoming a referrer A wallet registers a referral record with `register_referral_account`. The wallet signs, and any payer can pay the rent of the record. Each wallet can register one record. A record does not need a trading account first. `register_referral_account` for a wallet whose record already exists succeeds and changes nothing. The wallet that signs is the record's **authority**: it claims the share. The authority can hand the record to another wallet with `set_referral_authority`. The record's address does not change, and its links stay with it. ## Linking a wallet to a referrer A wallet links itself to a referrer's record with `set_referral`. * **Only the wallet can link itself.** The link is made for the wallet that signs. A payer can pay the rent, but nobody can link a wallet that is not theirs. * **One link, for life.** A wallet has at most one link. Once made, the link cannot be changed, moved to another referrer or removed. A second link for the same wallet is refused. * **A wallet cannot refer itself.** A link to a record whose authority is the same wallet is refused. * The link can be made in its own transaction or in the same transaction as a trade. Put the link **before** the trade in that transaction, so the first trade earns: a trade earns only when it was committed at or after the link. * **The referrer's record is made for you if it is missing.** Name the referrer's wallet when you link, and `set_referral` makes the referrer's record first. This works only while registration is open, only for a referrer wallet that already exists on chain and is a normal (on-curve) wallet, and the link's payer pays the record's rent. A wallet that does not exist on chain is refused (`ReferralReferrerMissing`, 6393), so a mistyped address fails instead of making a permanent link. The referrer can then claim with the same wallet; it does not register again. The `referrer` argument of `open` is not a referral link. It moves no money and creates no link. ## The discount A linked wallet pays a lower exit fee. The discount is a share of the exit fee: **10 % off** the fee the close would pay without a link. A link made before 2026-11-10 keeps its **25 % off**. * **Fixed in the link.** The discount rate is copied into the link when the link is made, and it never changes. A later change to the program's discount setting applies only to links made after it. * **Every close after the link.** The discount applies to every close of the wallet's positions that settles after the link exists. The time the position opened does not change this. * **Only where there is a fee.** A knockout pays no exit fee, so it has no discount. The same holds for any other close that pays no exit fee. * **It comes out of the protocol's part of the fee.** The pool's part of the fee does not change. Each discounted close emits a `ReferralDiscounted` event. It carries the fee without the discount (`fee_full`) and the amount saved (`discount`). The fee actually charged is on the close's `SettlementReceipt` event (`exit_fee_total`), so `fee_full` is `exit_fee_total` plus `discount`. ## The referrer's share When a linked wallet's trade settles, the referrer's record is credited a share of the **protocol's part** of that settlement: the protocol's part of the exit fee, after the discount, and the protocol's part of the loss tax. The share is moved to the program's referral vault and credited to the record. * **Which trades earn.** A trade earns the share only if it was committed at or after the moment the link was made. A trade committed before the link earns nothing, even if it settles later. * **What the share is computed on.** The share is computed on the protocol's part that the settle actually pays. The protocol's own part of a close is paid last, and not at all while any win is still owed (see [how a win is paid](/liquidity#how-a-win-is-paid)). A settle that pays the protocol nothing credits no share. * **The rate.** The rate is the record's tier. A record starts at the default tier and moves up as the revenue its linked wallets drive grows. That revenue is the record's running total of the protocol's part on which the share was computed. | Revenue driven by the record's linked wallets (USDC) | Rate, share of the protocol's part | | - | - | | Below 10,000 | 20 % | | 10,000 | 25 % | | 40,000 | 30 % | | 150,000 | 35 % | | 500,000 | 40 % | | 650,000 | 45 % | | 1,000,000 | 50 % | The tier rises when a record's total crosses a line and the record is refreshed with `refresh_referral`. Anyone can send it, for up to twenty records at a time. The rate applied to each settle is on its event, and it is never more than half of the protocol's part. ### How the share is recorded Each settle of a linked wallet's trade emits a `ReferralAccrued` event, after the settle's other events. It names the record and the position, and carries: | Field | Meaning | | - | - | | `base` | The protocol's part the share was computed on. 0 when the trade does not earn. | | `amount` | The share credited to the record. 0 when the trade does not earn. | | `rate_bps` | The rate applied, in basis points. | | `tier_bps` | The record's tier at the settle. | | `base_total` | The record's running total after this settle. | If the settle finds a fault at the referral accounts that the sender cannot cause, it emits `ReferralSkipped` instead, and the share goes to the protocol. A trade is never refused for it. ### When the discount and the share apply The discount and the share are applied by the settle of the position, when the settle carries the wallet's link and, for the share, the referrer's record and the referral vault. A settle of a linked book that leaves them out can be refused (`ReferralAccountsRequired`, 6306); one that is not refused applies no discount and credits no share. If you settle your own positions, include the three accounts. `config.referralFlags` holds the program's referral switches. One can stop the share for every link, one can stop the discount for every link, and one lets a settle of a linked book that leaves out the referral accounts be refused. A record can be disabled. A disabled record earns nothing more, its links stay, the wallets linked to it keep their discount, and it can still claim what it was credited. ## Claiming The record's authority withdraws the credited share with `claim_referral`. * It names an amount, or 0 to take everything credited and not yet claimed. An amount above that is refused. * It pays into any USDC token account, except three: the referral vault itself, the pool's vault account and the protocol's treasury. * A claim with nothing to pay does nothing. * Credited money stays on the record until it is claimed. A claim has no waiting period. Each claim emits a `ReferralClaimed` event with the amount and the record's lifetime total claimed. ## Minute players A Minute round is a Knockout position held by a player account that Minute derives from your wallet. The link of the wallet is copied to that player account with `bind_referral`: the copy names the same referrer, the same moment of the link and the same discount. Anyone can send it, and the sender pays the rent. Only a wallet's own link can be copied, so the copy always says what the wallet's link says. Once the copy exists, a Minute round gets the discount and earns the share under the same rules as any other trade. A round settled before the copy exists has no discount and credits no share. ## Reading it | What | Where | | - | - | | Program totals: USDC claimed by referrers, referrers who have claimed, linked wallets | [`GET /v0/referral`](/data-api) | | A link was made | the `ReferralLinked` event | | A record was registered | the `ReferralAccountRegistered` event | | A discount was given | the `ReferralDiscounted` event | | A share was credited | the `ReferralAccrued` event | | A share was claimed | the `ReferralClaimed` event | | A record's tier moved | the `ReferralRefreshed` event | | The referral switches | `config.referralFlags` | ## Using the SDK The SDK builds every instruction a wallet signs here, derives every address and decodes every account and event. Addresses passed to a builder are hex (`toHex`); decoded addresses are hex; money is `bigint` in USDC base units. Each builder returns a `BuiltInstruction`: turn it into a web3.js instruction with `ourInstruction`, then simulate and send it as on the [quickstart](/sdk/quickstart). ### Become a referrer The wallet signs. `payer` pays the rent of the record and can be the same wallet or an app. ```ts theme={"dark"} import { type PublicKey } from '@solana/web3.js'; import { referralRecordPda, registerReferralAccount, toHex, type BuiltInstruction } from '@rekt-trading/1000x'; export function becomeReferrer(wallet: PublicKey, payer: PublicKey): { built: BuiltInstruction; record: PublicKey } { const built = registerReferralAccount({ referrer: toHex(wallet), payer: toHex(payer) }); // The record's address comes from the wallet that registers it, and never moves. return { built, record: referralRecordPda(wallet).address }; } ``` ### Link a wallet, once The wallet being linked signs; `payer` can be an app. The record is the one derived from the referrer's registering wallet. Read the wallet's link address first: if an account is there, the wallet is already linked for life and a second link is refused. ```ts theme={"dark"} import { type Connection, type PublicKey } from '@solana/web3.js'; import { decodeReferralLink, referralLinkPda, setReferral, toHex, type BuiltInstruction, type ReferralLinkView, } from '@rekt-trading/1000x'; /** The wallet's link, or null when it has none. A link never changes, so one read is enough. */ export async function readLink(connection: Connection, wallet: PublicKey): Promise { const info = await connection.getAccountInfo(referralLinkPda(wallet).address, 'confirmed'); return info === null ? null : decodeReferralLink(new Uint8Array(info.data)); } export function linkToReferrer(wallet: PublicKey, payer: PublicKey, referrerWallet: PublicKey): BuiltInstruction { // Naming the referrer's WALLET lets the program make its record when it is missing. return setReferral({ referee: toHex(wallet), payer: toHex(payer), referrer: toHex(referrerWallet) }); } ``` `readLink(...)?.discountBps` is the discount frozen into the link. ### Link in the first trade `withReferralLink` puts the link into the trade's own transaction, so the first trade earns. The order the program accepts, per first trade: | First trade | Instructions, in order | | - | - | | Knockout | `init_trader_account`, `set_referral` (with the new book), the open | | Minute or Sprint | `set_referral`, `init_player`, `mark_minute_trader` (a wallet's own round, optional), the round's open | Each may come once before the trade's commit. `mark_referral_book` may not come before it; send it after the commit when you want it. ```ts theme={"dark"} import { type PublicKey } from '@solana/web3.js'; import { toHex, withReferralLink, type BuiltInstruction } from '@rekt-trading/1000x'; /** `firstTrade` is the trade's own instructions; `after` is 1 when it starts with `init_trader_account`. */ export function firstTradeWithLink( firstTrade: BuiltInstruction[], wallet: PublicKey, payer: PublicKey, referrerWallet: PublicKey, after: 0 | 1, ): BuiltInstruction[] { return withReferralLink(firstTrade, { referee: toHex(wallet), payer: toHex(payer), referrer: toHex(referrerWallet), after }) as BuiltInstruction[]; } ``` ### Read a referrer's earnings `referralEarnings` returns what an earnings screen shows, from the record and the settings on chain. Show its fields; compute no amount of your own. ```ts theme={"dark"} import { type Connection, type PublicKey } from '@solana/web3.js'; import { chainNowSeconds, decodeReferralConfig, decodeReferralRecord, referralConfigPda, referralEarnings, referralRecordPda, type ReferralEarnings, } from '@rekt-trading/1000x'; /** Null when the wallet has no record. */ export async function readEarnings(connection: Connection, referrerWallet: PublicKey): Promise { const [record, config] = await connection.getMultipleAccountsInfo( [referralRecordPda(referrerWallet).address, referralConfigPda().address], 'confirmed', ); if (!record || !config) return null; return referralEarnings( decodeReferralRecord(new Uint8Array(record.data)), decodeReferralConfig(new Uint8Array(config.data)), await chainNowSeconds(connection), // the chain's time, never your machine's ); } ``` | Field | Meaning | | - | - | | `claimable` | What a claim pays now: credited less claimed. | | `accrued`, `claimed` | Lifetime credited, lifetime claimed. | | `tierBps` | The record's tier. | | `rateNow.rateBps` | The rate on the next settle. | | `revenueDriven` | The record's running total that sets the tier. | | `nextThreshold` | The next tier line, its rate and the revenue still to drive; `null` at the top. | | `referees` | The wallets linked to the record. | | `refreshOwed` | The total has crossed a tier line that the record does not show yet. Send `refreshReferral([toHex(record)])`; anyone can. | ### Claim The record's authority signs. `destination` is a USDC token account, for example the wallet's associated token account. An amount of `0n` claims everything credited and not yet claimed. ```ts theme={"dark"} import { type PublicKey } from '@solana/web3.js'; import { claimReferral, toHex, type BuiltInstruction } from '@rekt-trading/1000x'; export function claim(authority: PublicKey, record: PublicKey, destination: PublicKey, amount = 0n): BuiltInstruction { return claimReferral({ authority: toHex(authority), record: toHex(record), destination: toHex(destination) }, amount); } ``` `setReferralAuthority({ authority, record }, newAuthority)` hands the record to another wallet. ### Settling your own positions A settle applies the discount and the share only when it carries the referral set: the owner's link, the record it names and the referral vault. Pass the set as the `referral` argument of `ix.settle`, and compose the transaction through the table `chooseSettleTable` picks: a settle with the set fits only through the shared referral table. ```ts theme={"dark"} import { type Connection, type PublicKey } from '@solana/web3.js'; import { chooseSettleTable, decodeReferralLink, referralLinkPda, referralSettleAccounts, toHex, type ChosenMarketTable, type ReferralSet, } from '@rekt-trading/1000x'; /** The set for a book's owner, or null when the owner has no link. */ export async function referralSetFor(connection: Connection, owner: PublicKey): Promise { const info = await connection.getAccountInfo(referralLinkPda(owner).address, 'confirmed'); if (info === null) return null; return referralSettleAccounts(toHex(owner), decodeReferralLink(new Uint8Array(info.data)).record); } /** The lookup table for the settle: the shared referral table when the set rides. */ export function settleTable(connection: Connection, market: PublicKey, set: ReferralSet | null): Promise { return chooseSettleTable({ market, referral: set !== null, required: [], fetchTable: async (address) => (await connection.getAddressLookupTable(address)).value, }); } ``` Then build the settle as on [settling](/sdk/settling#3-build-the-close) and pass the set: `ix.settle(accounts, seq, reason, feeds, set)`. A settle of a linked book without it can be refused (`ReferralAccountsRequired`, 6306); one that is not refused applies no discount and credits no share. For a Minute round the owner is the player account, so read the player's link. ### Events `decodeReferralEvent(bytes)` decodes any referral event and returns `null` for any other event. `decodeReferralAccrued`, `decodeReferralDiscounted` and `decodeReferralClaimed` decode one each. ## Refusals | Error | Code | When | | - | - | - | | `ReferralClosed` | 6305 | Registration or linking is closed. | | `ReferralAccountsRequired` | 6306 | A settle of a linked book left out the referral accounts. Pass the link, the record and the referral vault. | | `ReferralSelfLink` | 6307 | The wallet tried to link to its own record. | | `ReferralRecordDisabled` | 6308 | The record is disabled. Link to another record. | | `NotReferralAuthority` | 6311 | The signer is not the record's authority. | | `ReferralClaimDestinationRefused` | 6322 | The claim named one of the three refused accounts. Name another USDC account. | | `ReferralClaimTooLarge` | 6323 | The claim asked for more than is credited and not yet claimed. | A second link for the same wallet fails before the program's own checks run, because the link already exists. Questions: [support@asymmetra.xyz](mailto:support@asymmetra.xyz). # Risk Source: https://docs.rekt.money/risk What can go wrong, for traders and for the liquidity pool, in plain language. This protocol is early alpha and unaudited. > [!WARNING] > > **Knockout is early alpha software. It has not been audited by a third party. Engage at your own > risk, and only with money you can afford to lose entirely.** Read the rest before you trade. ## If you trade **You can lose your entire stake in under a second, and that is the design working correctly.** At 1000x the barrier sits a very small distance from your entry. A move against you that you would barely see on a chart can knock you out. There is no margin call and nothing to top up. **At the barrier you get nothing back.** The stake is gone. Hitting the barrier is a normal result, not a rare one, so size your stake for it. **Your position's collateral is capped**, at the maximum collateral in the config (`config.params.maxCollateral`, governed). The venue is fee-inclusive: any entry fee comes out of the budget you sign, so one open never debits more than that budget. Adding to a live position counts against the same collateral ceiling, so a double-down cannot take the position's collateral past it. **Doubling down on a winning position moves your barrier toward the price.** You may add collateral to a position that is already live. The 1000x is fixed by the position's tier, chosen at open, so an add buys size at market rather than posting margin: the entry becomes the average of what you paid, and both levels move with it. Adding while you are *behind* widens the runway; adding while you are *ahead* narrows it. It is a way to press a view, never a way to defend one — see [adding to a position](/how-it-works#adding-to-a-position). A double-down is an order too: it is priced at the next price after a short delay, or returned. A returned double-down keeps the time it added to your timer. Until it is priced, and for a short time after, you cannot close the position. **Closing costs a fee, and a close at a loss costs more.** A close at a loss pays a loss tax first, a share of the loss taken from what is left before the exit fee, so a loss costs you more than the move against you. The exit fee is a share of what the position is worth when it closes: a lower rate on a win, a higher rate on a loss, and a rate between the two for a close near your entry price. On a gain the terms also withhold part of the gain, so a target pays less than its multiple. A knockout pays nothing, so it carries no fee. The rates and a worked example of a win and of a loss are on [Fees and limits](/limits#how-a-win-is-calculated), with the date they were read. **A win is paid in full, and part of it may be paid later.** Your stake comes back at once and the profit is paid from the pool's free cash. What the pool cannot pay yet joins a queue and is paid in order, with no guaranteed time. See [how a win is paid](/liquidity#how-a-win-is-paid). **Funding is a governed rate, and the rate is 0.** It comes out of the payout and never out of your equity, so it does not move your barrier. Its rate is frozen onto your position at open: [Fees and limits](/limits) has it, and [the mechanism](/how-it-works#funding) the rest. **Your outcome is decided by the signed price of your market's feed, not the price on your own screen.** That price can differ from the venue you are watching, and you can be knocked out at a price you never saw. See [oracle risk](#risks-that-apply-to-everyone) below for what backs it. **Your entry is the next price, not the price on your screen.** An open is an order. It takes your stake when it lands, and the first price of the venue's price feed after a short delay sets your entry. The price can move in that delay, in either direction. If no usable price or no filler comes in time, the order is returned and the whole stake comes back. A returned order is a normal outcome, not a fault. **A close you ask for is a request, and its price is not locked.** The first price after a short delay prices it. Anyone may complete it, and the venue's keepers do. If nobody completes it inside the exit window, the next window's price applies, and a knockout price in between still ends the position. A request cannot be withdrawn, and you cannot send one in the first slots after your entry price (the minimum hold). **A knockout can be proved with a recent price.** Anyone may prove it with any signed price newer than your entry and up to a governed number of slots old. The move that ended your position can already have reversed by the time you look. **Opens can be refused or returned, and both are normal.** The protocol refuses an open when the venue or the market is paused, when a market is inside a scheduled event window, or when a market is outside or near the end of its trading hours. An order that lands is returned when its price does not come in time, does not meet the venue's quality rule, or does not fit the pool's cover rule at its fill (your whole stake comes back, with no fee). A client should show the reason, not retry blindly; see [error handling](/sdk/errors). **Settlement needs a transaction.** Your position does not close itself. It becomes *closable*, and anybody, including you, can then close it. **Nobody is paid for doing so:** a close is somebody spending SOL on your behalf. The venue runs keepers that close closable positions. That is a service, not a protocol guarantee, and you can close your own. **If no price can be obtained for a long time, a live position gets its stake back with no exit fee.** Until then a position stays open, and it can still be knocked out or reach its target once prices return. **The price feed can go down.** A single market can also stop opening when its price does not meet the venue's quality rule for an entry. While there is no price, an order you place is returned, no close can be priced, and positions wait; the no-price close above is the backstop. **An operator stop can pause closing.** A guardian key can freeze the oracle. Opens, adds and the no-price close are refused, and every priced close fails for want of a price, so a live position cannot be closed until the freeze is lifted. It can also disable settles (no close for any reason, including a knockout). Only the protocol's config authority can lift either. While either switch is set you cannot exit. Both switches are public fields on the config account (`config.oracleFrozen`, `config.settlesDisabled`). An order or a double-down that is waiting for its price when a stop starts is not lost: it is filled or returned, at the latest once the stop ends. ## The liquidity pool **The pool is the counterparty to every trade, and losses are real.** It funds every win and keeps every loss, and none of that is a promise of a return — a run of trader wins draws the pool down, same as it would for any counterparty on the losing side of a run. In short: * **No deposit and no redemption.** The program has no instruction to deposit into the pool or to redeem from it. * **A win may be paid later.** A win is paid in full, but the pool pays what it cannot pay at once from a queue, in order, with no guaranteed time. * **No insurance fund standing behind the pool.** See [the insurance fund](/liquidity#the-insurance-fund). * **Limited capacity.** A run of large wins can draw the pool down, and what it cannot pay at once is paid from the queue. Each of those, in full: [the liquidity pool](/liquidity). ## Risks that apply to everyone > [accordion] Smart contract risk > > The protocol has been reviewed adversarially in-house, and its settlement > arithmetic is checked by golden test vectors emitted from the engine itself. **That is not the same as a third-party audit, and there has not been > one.** A bug in an unaudited program can cost you everything in it. > [accordion] Oracle risk > > Every outcome depends on a signed price from the market's price feed. The program accepts a > price only when its signature checks out. An order is filled only by the first price at or after its target, and only when > that price meets the venue's quality rule for an entry; a close is priced by the first price at > or after its target. The program sees the signed price, not how it was formed. No oracle design > removes the risk that a reported price differs from where you believe the market is. > [accordion] Governance risk > > Fees, bounds, caps, tiers and delays are **governed parameters**. They can be changed > on chain by the protocol's authority, without your consent. Changes are public and readable, > and a position already open keeps the terms it was opened under. A separate guardian key can > freeze the oracle or disable settles at once, with no notice; only the protocol's authority can > lift either. The program itself has an upgrade authority: check who holds it and decide for > yourself whether you are comfortable. > [accordion] Solana network risk > > Congestion, outages and failed transactions are properties of the underlying network, not of > this protocol. A transaction that does not land is a transaction that did not happen — which > can matter at the moment you want to close. > [accordion] Regulatory and tax risk > > Knockout is a program on Solana. You open and close positions with transactions you sign, > against the protocol's pool, and every term is readable on chain. How any law or tax > rule applies to a position is a question this documentation does not answer. > Nothing in this documentation is financial, legal or tax advice. ## When the venue pauses The team can pause the venue, or a single market. A pause stops **new orders and new double-downs**, and it stops a take-profit from being proved and a target from being moved. A pause of the whole venue also stops the delivery of funded queue money. It does not stop you leaving: closes, timer ends and knockouts keep working, and every open position can still be closed. An order already placed is still filled or returned as usual. The team reopens the venue by hand. In a serious incident the team can also stop pricing altogether, as described under "An operator stop can pause closing" above. The operator can also wind the venue down: new orders and adds stop, and open positions still end by their own rules. ## What is unfinished Named plainly, because "alpha" on its own tells you nothing: * **No third-party audit.** * **Live parameters can change.** Every open is 1000x; fees and caps are governable; every change is on chain. * **The pool's capacity is limited,** so a large win can be paid late: part of it is paid from the queue, in order. * **This is an experiment, built in public.** Parameters, limits and features can change, and the program itself can be upgraded. Do not put in more than you can afford to lose. * **The stack is young.** Where the SDK cannot prove something, it says so rather than implying coverage it does not have. ## Verify rather than trust Everything that governs your money is on chain and readable. **Do not take this page's word for it.** [The venue](/venue#read-it-on-chain) already gives you the three commands and the SDK exports that check it yourself — the config PDA, the vault PDA, and the program's own upgrade authority, which is who can change the program that holds your funds. Run them. **We would rather you verified it than believed us.** # Building an agent Source: https://docs.rekt.money/sdk/agents The operating brief for an LLM driving Knockout: the loop, the refusals, the units, orders and closes, and the five things an autonomous client must never do. This page assumes the reader is a capable model with no prior context, building a client that decides and sends without a human watching each action. It is short, dense and imperative. Every section links to the page that explains it properly — read this first, then follow the links you need. ## Building a bot? Bots and agents are welcome here. Every rule is public and on chain, so your program can price its own costs exactly instead of guessing. **What a trade costs:** no fee to open; on a close, a loss tax on a loss, an exit fee on the exit value and the terms' share of a gain (see [the fees page](/limits#what-a-trade-costs)). Read the exact terms an open would freeze with `openFeeTerms()` and its outcome with `openPreview()` before you send. Orders fill at the venue's next price about 2 seconds after they land. **Do not judge a strategy from the fee table alone:** model your own edge, then measure it. [Wheelman](/tools/wheelman)'s paper mode (`--paper`) trades on live prices with no money, and its `replay` price source (`PRICE_SOURCE=replay`) runs your strategy in paper mode on recorded prices. Settled trades are public in the [Data API](/data-api). These docs describe costs and rules. They do not suggest a strategy and promise no profit. > [!WARNING] > > Knockout is a **barrier product**. A position can be knocked out by a small move and > end at zero. An autonomous client is a client that can lose money quickly and without anyone > noticing. Build the read path and the refusal path before you build the send path. ## The loop Five steps, in this order. Skipping step 2 or 3 is how a client ends up learning the protocol from reverted transactions. **1. Read the protocol** Config, vault and market, decoded from the chain — [Read the protocol](/sdk/reading). Addresses are derived locally with `configPda`, `vaultPda`, `marketPda`, so you never trust an address printed on a page. **Never cache `config.params`**: every field in it is governed and can move without a program upgrade. **2. Price it** `openPreview` / `costToOpen` tell you what the trader is actually charged and the gross payout at the target, which is before the exit fee and the share of the gain the terms withhold. A losing close above the barrier pays what is left after the loss, less a loss tax on that loss and then the exit fee: see [what a close pays](/sdk/positions#what-every-close-would-pay-right-now). Do not recompute protocol arithmetic yourself — a second derivation of a number is how a client and a chain come to disagree. **3. Ask what would refuse it** `openGates` and `settleGates` return every gate with the measured value and the threshold — [Reading gates](/sdk/gates). Branch on the first failing gate. **Order is a per-function property.** `openGates` follows the program's order for an open. `settleGates` emits its own sequence and does not reproduce the program's settle order row for row: it places the reason row by the cause it reports, ahead of the price row or behind the exponent row. Neither report reads the guardian flags; read `config.oracleFrozen` and `config.settlesDisabled` yourself. An agent that sends to find out is paying for information it could have had for free. **4. Send, then wait for the step to end** **An open, an add and a close request carry no quote.** Build an open with `ix.open(accounts, args, priceAccountsFor(market, config, 'open'))`, an add with `addCollateralFor` and a close request with `requestCloseFor`, sign, send, and then wait for the event that ends each step: `EntryFilled` or `OpenVoided` for an order, `CollateralAdded` or `AddReversed` for an add, `SettlementPriced` for a close. A landed transaction is an order or a request, never the result. [Orders and closes](/sdk/orders) is the contract, and [Opening](/sdk/opening) has the code. A quote matters only if you send an instruction that carries one yourself: a `settle`, a `stamp_book` or a `set_take_profit`. Those age out in **slots, not seconds**, judged when the program runs rather than when you obtained the quote. **Obtain a new quote immediately before signing**, sign locally, and never put a human approval between the two. See [Settling](/sdk/settling) and [Quotes and freshness](/sdk/quotes), and [Getting prices](/sdk/prices) to obtain one. **5. Reconcile** Compare what you predicted against what the chain moved. A client that never checks is a client that will be wrong quietly. Decode the events rather than inferring from balances: the SDK exports `decodeSettlementPriced`, `decodePositionOpened`, `decodePositionStamped`, `decodeEntryFilled`, `decodeOpenVoided`, `decodeAddReversed` and `decodeSettlementReceipt`, and `readTradeHistory` reads them back off a cluster. Join every event on `openerTag`. ## Refusals: branch on `retryable`, never on the name The error catalogue is generated from the SDK's client IDL, so it cannot drift from what the chain raises — [Error handling](/sdk/errors). The one field that matters to an autonomous client is `retryable`: | `retryable` | Do | | - | - | | `never` | Fix the request. Retrying is an infinite loop. | | `after-state-changes` | Re-evaluate when the world moves on its own — a settle, a new slot. Back off. | | `after-governance` | Stop retrying on a timer. Only an instruction signed by the venue's config authority clears it; poll the flag the `fix` names and alert an operator. | | `immediately` | Retry on the next slot. These are almost all price freshness. | Resolve with `errorForCode` / `errorForName`. **Do not pattern-match error strings.** The names are an ABI and the codes are stable; your regex is neither. For the order and close codes, 6203 to 6238, bind to `retryClassOf(code)`: it says "done", "send the other instruction" and "retry with the right quote", which `retryable` cannot. Two refusals that mean something different from what they sound like: * **`PositionSlotsFull`** — the *trader's book* is full, not the venue. A book holds a fixed number of positions, chosen when it was created and changeable afterwards. * **`SideStakeCapReached`** — raised only on a market that has a side limit set. No market has one set. If one is set and the side is full, back off; do not spin. A pool that cannot cover an order is not a refusal: the order is returned with the whole stake. ## What constrains you, whatever you are trying to do These hold on chain and no client can talk its way past them: * **The cover rule.** A fill is admitted only if the pool can cover it. The number of concurrent positions the venue admits depends on the pool and the queue. An order that does not fit is returned with the whole stake and no fee: treat it as a state, not a fault. * **A win may be paid later.** A win is paid in full, but part of it may be paid later, in order, and `SettlementPriced.trader` is only what was paid now. Never present it as the amount won: read `SettlementQueued`. * **Money in = money out on every path.** The program never mints and never burns. * **The pauses close the entry, not the exit.** A pause of the venue or of one market stops opens, adds and take-profit retargets; `settle` continues. An order already placed is still filled or returned. * **An order is not a position, and a request is not a close.** The entry is the venue's next price after a short delay, and the exit is the first price after the close's target, by the window rule. Never show a price from the tap as the entry or the exit. * **A stop can freeze both prices and closes.** An oracle freeze refuses opens, adds, close requests, expiry marks, `stamp_book`, `lastResort` and the return of an order or add that needs a price, and starves `settle` and `set_take_profit` of a price. A settle stop refuses all of those, every `settle` reason, `set_take_profit` and the return of an unfilled order or add. Only the config authority lifts either. Read `config.oracleFrozen` and `config.settlesDisabled`, and treat either as a stop, not a retry. * **A market with trading hours only accepts opens and adds during its own session.** The calendar is on the market account (`market.sessions`). Read it, or call `availability()` for the state and the next open, and do not assume that a market is always open. See [markets](/markets). ## Units * USDC in **base units**, 6 decimals. `250000` is \$0.25. * A payout can be large relative to collateral. Format money as dollars in anything a human reads; a figure printed as `25007500` will be misread as twenty-five million. * Rates and limits are in basis points or micro-basis-points on chain. Read them from the account, never from a constant you copied. ## Who signs An open, an add and a close request carry no quote, so a person can approve each one in a wallet, and an autonomous client signs locally. The instructions that carry a quote are `set_take_profit` and any `settle`, `stamp_book` or `prove_price` you send yourself. A quote ages out in slots, so a human approval between the quote and the send cannot land: sign those locally. If you are trading a book that is not your own, one option is for the owner to authorise a **session-key delegate** your agent signs with; if you are trading your own, you are already a local signer. How you sign is your decision. Put any human approval on the **authorisation**, which carries no price and races nothing. If you choose the program's session-key delegate, it is five moves — [session keys](/sdk/sessions) has working code for each: 1. **Generate.** An ordinary keypair, made where the trades are signed. It is not the owner's wallet and is never derived from it. 2. **Authorise.** `authorizeSession` — one instruction the owner signs, setting the expiry, the spend window and the SPL token allowance together. 3. **Fund it.** The fee payer must sign, so on this route it is not the human — the session key itself, or a separate sponsoring fee payer you add. Give whichever pays its own lamports and watch the balance. 4. **Sign every trade with it.** `authority` is the session key, `delegate` is `delegatePda(owner).address`, and the book, the token account and the money all stay the owner's. 5. **Revoke when the mandate ends.** `endSession` closes the account and drops the SPL allowance in one instruction, in the same slot, and returns the rent. Gate before you send: `delegateGates` covers the four refusals `openGates` does not model, and `sessionAllowanceGates` covers the SPL allowance — a **total that draws down and never refills**, which is what actually ends most long sessions, arriving from the token program as `InsufficientFunds` in none of this program's error shapes. > [!NOTE] > > **A session key can open AND request a close**, unless its grant carries the no-close > restriction. The program authorises a `request_close` for the owner or for an unexpired session key > bound to them, and the request saves a wallet prompt and races nothing. The settle that completes > it is sent by anyone, and the other six close reasons are permissionless and need no signature > from either. ## Five things an autonomous client must never do 1. **Never route around a refusal.** A guard that refuses you knows something you do not. Read the gate, fix the request. 2. **Never cache governed state.** `config.params`, market parameters and the session calendar all move on chain. Re-read them, and show how old your copy is. 3. **Never put a credentialled RPC endpoint in a command line, a log, a commit or a screenshot.** Reference it by variable name — [Installation](/sdk/installation). 4. **Never present a model output as a fact.** An estimate from your own model is yours to compute and yours to label. What the chain settled is a fact; what your model expects is not. 5. **Never sign a second order for the same intent after a timeout.** Inside one blockhash life, send the same signed bytes again. A second signature is a second order, and both can land. ## Where to go next | You want | Read | | - | - | | a bot that quotes, opens and closes | [Quickstart](/sdk/quickstart) | | to run a strategy on paper or on recorded prices, with no money | [Wheelman](/tools/wheelman) | | a working read path in one file | [Read the protocol](/sdk/reading) | | the docs as an MCP server, and a skill file | [Build with an AI agent](/sdk/ai) | | **orders, fills, closes and what never to assume** | **[Orders and closes](/sdk/orders)** | | **to sign with a session key** | **[Session keys](/sdk/sessions)** | | to understand `6007` and what to do about it | [Quotes and freshness](/sdk/quotes) | | every refusal, before you send | [Reading gates](/sdk/gates) | | to open a position | [Opening](/sdk/opening) | | to read and value a book | [Positions](/sdk/positions) | | to close a position | [Settling](/sdk/settling) | | to decode accounts, events and errors | [Reference](/sdk/reference), [Error handling](/sdk/errors) | | what the product actually is | [How it works](/how-it-works), [Risk](/risk) | # Build with an AI agent Source: https://docs.rekt.money/sdk/ai Give an agent these docs three ways: an MCP server it can search, llms.txt, and a skill file it can load. Then let it write the bot. These docs are written for people and for agents. An agent that builds a bot, a keeper or an interface on Knockout can read all of it without a browser. This page shows the three ways in and what to give the agent first. ## 1. The docs as an MCP server The docs site is a hosted MCP server. A client that connects to it can search every page and read the result. ```text theme={"dark"} https://docs.rekt.money/mcp ``` > [tab] Claude Code > > ```sh theme={"dark"} > claude mcp add --transport http rekt-docs https://docs.rekt.money/mcp > ``` > [tab] Cursor > > Add this to `.cursor/mcp.json`: > > ```json theme={"dark"} > { > "mcpServers": { > "rekt-docs": { "url": "https://docs.rekt.money/mcp" } > } > } > ``` > [tab] Any other client > > Add a remote MCP server over HTTP with the URL above. It needs no key and no account. ## 2. `llms.txt` and the page text | URL | What it is | | - | - | | `https://docs.rekt.money/llms.txt` | An index of every page, one line each. Start here. | | `https://docs.rekt.money/llms-full.txt` | Every page in one file, for a model with a long context. | | `https://docs.rekt.money/sdk/orders.md` | One page as plain text. Add `.md` to the address of any page. | | `https://docs.rekt.money/skill.md` | The skill file, described below. | ## 3. The skill file [The skill](https://docs.rekt.money/skill.md) is one file an agent loads before it works on Knockout. It says what Knockout is, how to quote, open, add, close and settle, how to read positions and queued claims, how to handle a refusal, and the limits and hours. It carries no more than a trader needs. Install it where your agent keeps skills. For Claude Code: ```sh theme={"dark"} mkdir -p ~/.claude/skills/rekt-knockout curl -fsSL https://docs.rekt.money/skill.md -o ~/.claude/skills/rekt-knockout/SKILL.md ``` Use `.claude/skills/rekt-knockout/SKILL.md` inside a project to scope it to that project. Another agent that loads `SKILL.md` files takes the same file in its own skills folder. ## What to ask the agent A good first prompt names the outcome and points at the page that has the code: ```text theme={"dark"} Read the Rekt Knockout quickstart and build me a bot that opens a $1 long on BTC, waits for the fill and closes it. Dry run first. Do not send anything until I say so. ``` The [Quickstart](/sdk/quickstart) is a working bot. The agent can run it, change it and extend it. [Building an agent](/sdk/agents) is the operating brief for an agent that decides and sends without a person watching each action. ## Try it with no money An agent can trade on paper first. [Wheelman](/tools/wheelman), a bot and command line built on the SDK, has a paper mode: `wheelman open BTC long 1 --paper` simulates the fill and sends nothing, and it needs no SOL or USDC. Wheelman runs from a clone of its repository; the [Quickstart](/sdk/quickstart#try-it-with-no-money) has the commands. A paper result does not say what live trading pays. A dry run is not a paper trade. It simulates the real transaction on mainnet, so the wallet must hold SOL and USDC. ## Rules to give any agent that holds a key * **Dry run first.** Simulating costs nothing. Sending costs a stake. * **Start small.** The smallest stake is \$0.20. See [Fees and limits](/limits). * **Keep keys and RPC endpoints out of the prompt and out of logs.** Give the agent environment variable names and nothing else. * **A refusal is information.** Branch on the retry class. Do not loop on a refusal that says never. * **Never sign a second order for the same intent after a timeout.** Send the same signed bytes again. * **At the barrier you receive nothing.** An agent must say so to anyone it trades for. Questions go to [support@asymmetra.xyz](mailto:support@asymmetra.xyz). # Error handling Source: https://docs.rekt.money/sdk/errors The refusals a client meets, with a cause, a fix, and the one thing a name cannot tell you: whether retrying can ever help. The error catalogue is **generated from the SDK's client IDL**, so it cannot drift from what the chain actually raises. What is hand-written is the part a name cannot carry: what caused it, what to do instead, and whether retrying is useful or an infinite loop. This page lists the refusals a client meets. `catalogue()` holds every code the program can return. > [!WARNING] > > An agent that retries `RungBelowFloor` loops forever. One that gives up on `NoFreshPrice` fails > a trade that would have landed on the next slot. **Branch on `retryable`, never on the name.** ## The four retry classes | `retryable` | Meaning | What a client should do | | - | - | - | | `never` | The request itself is wrong. | Fix the request. Show the user what to change. | | `after-state-changes` | The request is fine; the world is not ready, and it will get ready on its own — a clock, a settle, the price, a feed. | Re-evaluate when state moves. Back off for seconds to minutes. | | `after-governance` | The request is fine, and only an instruction signed by the venue's config authority (`config.authority`) clears the refusal — a pause lifted, a flag set. Nothing changes on its own. | Do not retry on a timer. Poll the flag the `fix` names, back off slowly, and tell an operator. The venue's status page is [status.rekt.money](https://status.rekt.money). | | `immediately` | Transient. | Retry on the next slot. These are almost all price freshness. | Switch on all four. A client that folds `after-governance` into a default branch retries a venue-wide stop every few seconds. > [!NOTE] > > **The codes of orders and closes (6203 to 6238) have a finer class.** `retryClassOf(code)` returns one of > nine classes for every code the program can raise, and `RETRY_CLASS_LABEL` has the words: for > example "retry after the state changes", "retry with the right quote", "send the other > instruction" and "treat as done". `contextOf(code)` adds the note for a code whose action depends on what > was sent. Bind to the class, not to a remembered number. The table a client meets is under > [orders, closes and stamps](#orders-closes-and-stamps). ## Resolving an error ```ts theme={"dark"} import { errorForCode, errorForName, type ProgramErrorInfo } from '@rekt-trading/1000x'; export function explain(code: number): string { // null for a code this program cannot produce — do not assume every custom code is ours. const info: ProgramErrorInfo | null = errorForCode(code); if (!info) return `custom program error ${code} did not come from this program`; return [ `${info.name} (${info.code})`, info.msg ?? '', `Cause: ${info.cause}`, `Do this: ${info.fix}`, `Retry? ${info.retryable}`, ].join('\n'); } export const byName = errorForName('NoFreshPrice'); ``` ## Read the code against the program that failed The venue, Minute and the games programs use the same numbers for different errors, and a refusal raised inside a CPI arrives with the outer instruction's index and the inner program's code. A venue `6056 PositionSlotsFull` raised inside a game program's entry looks like `{"InstructionError":[2,{"Custom":6056}]}`, the same as that program's own `6056` would. Only the logs say which program refused: the program that raised the error writes the first `Program failed` line, and each caller repeats it. `refusalOf(err)` reads the logs from what the cluster returns (`SendTransactionError.logs`, a confirmed transaction's `meta.logMessages`, a simulation's `value.logs`) and names the code by the program that raised it. `refusalFromLogs(logs)` does the same from the log lines. ```ts theme={"dark"} import { refusalOf } from '@rekt-trading/1000x'; export function explainFailure(err: unknown): string { const r = refusalOf(err); if (r === null) return 'no refusal'; // `program` is the raiser: 'venue', 'minute', 'other' (see programId), or 'unknown' when there was no log. if (r.name !== null) return `${r.program} ${r.name} (${r.code})`; // No log: give every reading, and pick none. if (r.program === 'unknown') return r.readings.map((x) => `${x.program} ${x.name}`).join(' or ') || `code ${r.code}`; return `program ${r.programId} refused: ${r.detail}`; } ``` | Field | What it is | | - | - | | `programId`, `program` | The program that raised the error, and its name. | | `code`, `name`, `msg` | The code, and its name and message from that program's own table. `name` is `null` for a program this table does not cover, and `code` is `null` for a failure that is not a program error (compute exhausted). | | `depth` | 1 for a top-level instruction, 2 for a CPI from it. | | `outerProgramId`, `outerProgram` | The top-level program of the failed instruction: the game program, for a venue refusal inside its CPI. | | `readings` | Every table's reading of the code. One entry when the raiser is known, all candidates when it is not. | Pass the whole log. A log cut at the runtime's size limit can lose the raiser's line. ## Catching a refusal Every write path in the SDK raises `ProgramRefusal`, which carries the whole catalogue entry rather than a string — because an interface has to render the fix next to the failure, and a caller has to branch on `retryable` without parsing prose. ```ts theme={"dark"} import { ProgramRefusal } from '@rekt-trading/1000x'; export async function withRetry(action: () => Promise, attempts = 3): Promise { for (let i = 0; ; i += 1) { try { return await action(); } catch (e) { if (!(e instanceof ProgramRefusal)) throw e; switch (e.retryable) { case 'never': // The request is wrong. Retrying is a loop; surface the fix instead. throw new Error(`${e.info.name}: ${e.info.fix}`); case 'after-governance': // Only the config authority clears it, and nothing changes on its own. Do not retry on a // timer: surface the fix, which names the instruction and the key, and alert an operator. throw new Error(`${e.info.name}: ${e.info.fix}`); case 'after-state-changes': case 'immediately': break; } if (i >= attempts) throw e; // `immediately` is a slot away; `after-state-changes` deserves real backoff. A mainnet slot // is about 215 ms, and it moves: measure it (`getRecentPerformanceSamples`) if the margin // matters to you. const waitMs = e.retryable === 'immediately' ? 215 : 2_000 * (i + 1); await new Promise((r) => setTimeout(r, waitMs)); } } } ``` ## The refusals a client actually meets Everything below is a real entry in the catalogue. Names, codes and messages come from the client IDL. ### Orders, closes and stamps An open and an add are orders, and a close is a request. The rules are on [orders and closes](/sdk/orders). These are the refusals a client meets on that path. | Instruction | Error | What the client does | | - | - | - | | `open` | `SideStakeCapReached` (6224) | Raised only on a market that has a side limit set. No market has one set. If one is set and the side is full: try later, or the other side. | | `open`, `add_collateral` | `TimerBelowFloor` (6225) | Use a timer of at least the timer floor (26 seconds by default; read `config.timerFloorS`), or none. On a feed-kind-4 market the timer must also end after the fill window. | | `open`, `add_collateral` | `ProtocolPaused` (6046), `MarketPaused` (6047), `OracleFrozen` (6190), `SettlesDisabled` (6191) | The venue or the market is stopped. Do not retry in a loop. | | `add_collateral` | `AddsDisabled` (6212), `EntryNotFilled` (6203), `AddPending` (6211), `ExitPending` (6213) | Adds are off; wait for the entry; wait for the earlier add; a close is on its way. | | `request_close` | `MinimumHoldNotMet` (6103), `MarketHoldNotMet` (6236) | Wait for the hold. `closableFromSlotOf` gives the first slot. | | `request_close` | `ExitPending` (6213) | The close is already requested. Treat it as success. | | `request_close` | `ModeBitOff` (6228) | Close requests are switched off. Do not retry in a loop. | | `request_close`, `mark_expiry`, `stamp_book` | `OracleFrozen` (6190), `SettlesDisabled` (6191) | The venue is stopped. Do not retry in a loop. | | `settle` | `ExitNotAnchored` (6214), `ExitQuoteNotYetDue` (6216), `NotWindowQuote` (6217), `ExitReasonMismatch` (6215) | Request or mark first; wait for the target slot; use the quote of the current window; send the recorded reason. | | `settle` | `FeeTermsTableRequired` (6239), `QuoteOutsideSession` (6295) | The position froze fee terms and this close pays a gain or a fee: append the market's fee-terms account (`priceAccountsFor` adds it). On a market with trading hours, a quote signed at or after the close of the session that holds the deadline cannot price the position: do not retry with a later quote, the position ends at par by `lastResort` once it is due. | | `stamp_book` | `ProofNotAfterEntry` (6218), `ProofTooOld` (6219), `TakeProfitProofTooEarly` (6220) | That quote can never prove it: it is not after the entry, it is too old, or it is before the target was moved. | A returned order (`OpenVoided`) and a returned add (`AddReversed`) are not refusals. They are normal outcomes, and the stake comes back (`refundTotal`). ### Opening An open carries no quote, so no row below can judge one: the fill judges the first price, and a price that fails returns the order whole. | Error | Code | Retry | What it means | | - | - | - | - | | `OracleFrozen` | 6190 | after-governance | The guardian has frozen the venue's oracle. Opens and adds are refused, ahead of every other row; `SettlesDisabled` (6191) refuses them right after it. Only the config authority lifts either. Read `config.oracleFrozen` and `config.settlesDisabled`. | | `ProtocolPaused` | 6046 | after-governance | Governance has stopped new positions protocol-wide. The pause stops opens, adds and take-profit changes. A close and a settle still run. Only the config authority lifts it; the pause has no expiry. | | `MarketPaused` | 6047 | after-governance | This one market is closed to new positions and to take-profit changes. Others may be open. A close and a settle still run. Only the config authority reopens it; the pause has no expiry. | | `MarketClosed` | 6094 | after-state-changes | The market's session calendar is shut. Opens resume when the next window opens: `availability()` reports that instant as `opensAt`, and `nextSessionOpenS(market, now)` returns it. `openGates` reports this on `open.session`. | | `SessionEndsBeforeTenor` | 6095 | after-state-changes | The session is open, but after the market's settlement buffer less than five minutes of life is left to sell. Open earlier, or in the next session. `openTenorS` gives the life an open would get now; `openGates` reports this on `open.session`. | | `InsideEventWindow` | 6048 | after-state-changes | A scheduled event window. Opens resume when it ends. | | `CollateralOutOfRange` | 6049 | never | The stake is outside the governed bounds. Read them from the config account. | | `LeverageAboveMarketTier` | 6148 | never | The `tier` argument is above this market's own. Every live market sells 1000x, so every open is 1000x: send `tier: 0`, which asks for the market's own. Read `market.tier` and offer nothing above it. | | `LeverageBelowMinTier` | 6181 | never | The `tier` argument is below the venue's leverage floor for this market, so a lower leverage than 1000x lands here. The floor is `min(config.minTier, market.tier)` — resolve it against the market's own tier, not from `config.minTier` alone. `tier: 0` asks for the market's own and can never land here. | | `RungBelowFloor` | 6116 | never | The rung is tighter than `RUNG_FLOOR_BPS` (20,000 bps = 2.00x). `rung_bps` is basis points of stake, not a whole multiple — passing `2` asks for 2 bps and lands here. | | `RungAbovePayoutCap` | 6117 | never | The rung is above `payout_cap_multiple` — **the one take-profit ceiling**. Clamp to it, read from the config account. | | `PositionSlotsFull` | 6056 | after-state-changes | Every slot is in use. A slot frees only when a settle for it lands: close one, or grow the book with `resizeTraderAccount`. | A market with trading hours — see [markets](/markets) — refuses an open or an add when its session is closed (`MarketClosed`) or too close to its end (`SessionEndsBeforeTenor`). Both clear on their own, need no governance, and are not a mistake in the request. `availability()` says when the market opens. ### Settling | Error | Code | Retry | What it means | | - | - | - | - | | `PositionNotFound` | 6057 | never | No live position carries this sequence number. Your handle is stale. | | `NoFreshPrice` | 6007 | immediately | No quote cleared the slot age, the millisecond age and the signature floor **at the moment the program ran**. The refusal a settle meets most — [quotes and freshness](/sdk/quotes) is the page about it. Re-quote and resend; do not report it as a failed trade. | | `SettlesDisabled` | 6191 | after-governance | The guardian has disabled settles. **Every close reason is refused**, `knockout` and `lastResort` included, and so are opens, adds, close requests, expiry marks, `stamp_book`, `set_take_profit` and the return of an unfilled order or add. Only the config authority lifts it. Poll `config.settlesDisabled`. | | `NotPositionOwner` | 6072 | never | A `voluntary` close is authorised by the owner **or** by an unexpired session key bound to them. 6072 is raised only when no delegate account was supplied and the signer is not the owner. | | `MinimumHoldNotMet` | 6103 | after-state-changes | `voluntary`, `takeProfit` and `userExpiry` must wait the minimum hold from the open or the last add: `resolveMinHoldSlots(config.minHoldSlots)` slots. `knockout` and `lastResort` are never gated. `tenorExpiry` is gated only on a market with a session calendar; on a market with no session calendar it is not. | | `LastResortNotYetDue` | 6192 | after-state-changes | A `lastResort` close is legal on two grounds only. The market is dark: no posted price for 24 hours (`GovTable.darkAfterMin`), which needs the governance table among the remaining accounts. 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. A position with the indefinite tenor has only the dark ground. While a fresh price exists the close is refused `LastResortPriceAvailable` (6193): settle at market with a priced reason. | While the oracle is frozen, a `lastResort` close is refused `OracleFrozen` (6190) and every priced close fails `NoFreshPrice` (6007). If `NoFreshPrice` repeats on a settle, read `config.oracleFrozen` before you retry again. ### Payout destination | Error | Code | Retry | What it means | | - | - | - | - | | `PayoutDestinationWrongMint` | 6151 | never | The destination is not a token account on the vault's mint. | | `PayoutDestinationFrozen` | 6154 | never | The destination is frozen and could not receive a settlement. Offer an unfrozen account the trader owns. | ### Adding to a position `add_collateral` is an open in every respect but one — it grows a slot instead of creating one — so **every refusal in the *Opening* table above can also refuse an add**, including the guardian freeze, the pauses and the event window. These are its own. An add carries no quote: the freshness gate does not apply, and an add whose price is at or through a level is returned (`AddReversed`) rather than refused. | Error | Code | Retry | What it means | | - | - | - | - | | `MinCollateralOutRequired` | 6168 | never | `min_collateral_out` (open) or `min_added_collateral_out` (add) was `0`. It is **mandatory**: the caller signs a floor on the position SIZE, not a debit ceiling, and `0` is refused by name. Set it to your predicted collateral — never a token value like `1`, which satisfies the check and protects nothing. | | `BudgetBelowCollateralFloor` | 6169 | never | The budget resolved to a smaller position than your floor — a fee rose between quote and execution. Nothing was charged. Re-quote and raise the budget, or lower the floor (never to zero). | | `BudgetExceedsMaxCollateral` | 6170 | never | The budget buys more than `max_collateral`. Over-budget is **refused, not clamped**. Lower the budget to at most the cost of a max-collateral position; `sizeForTotal` reports that total when it refuses. | > [!WARNING] > > **`CollateralOutOfRange` (6049) answers three different facts on an add, and only one of them is > worth retyping.** The minimum binds on the **increment**; the maximum binds on the **total**. So > the code means the increment was under the floor, *or* the new total would be over the ceiling, > *or* — the case that traps a user — the position already holds more than > `maxCollateral − minCollateral`, so **no legal increment exists at all** and every value the > trader types will be refused. > > A client must compute the admissible interval and render it, rather than showing one code and a > text box. For example, with a minimum stake of $0.20 and a maximum of $1,000, a position holding > more than **\$999.80** can take no add. ### Sessions, the pool and Minute The refusals of a session key are on [session keys](/sdk/sessions#the-refusals-a-session-meets), and `delegateGates` predicts them. A session usually ends at the token program with `InsufficientFunds` when its allowance is spent, in none of the shapes on this page: `sessionAllowanceGates` is the only thing that predicts it, and `renewSession` is the only call that resets all three clocks — expiry, window and allowance — together. `MinuteDisabled` is on [integrating Minute](/minute/integrating#markets-the-venues-per-market-gate). Minute raises codes of its own, 6000 to 6050, and those numbers overlap the venue's: decode a code by the program that raised it (`minuteErrorForCode` for Minute). The venue's own 6050 (`RungAboveMarketCap`) is reserved and raised by nothing. `catalogue()` holds every other code the venue can return, each with its cause, its fix and its retry class. ### Commit shape, take-profit, sessions and on-chain oracle markets (6346 to 6373) These codes are grouped by what a client does. `catalogue()` and `errorForCode` hold each one with its cause, its fix and its retry class. **Retry in the next slot (`immediately`).** 6360 to 6366 (`BedrockStatusNotOk`, `BedrockPriceTooOld`, `BedrockConfidenceTooWide`, `BedrockTooFewOperators`, `BedrockConfigEpochMismatch`, `BedrockSmoothingRefused`, `BedrockExpoUnsupported`): the oracle has no usable price in this slot. **Wait for a state change (`after-state-changes`).** 6347 `AddInOpenSecond`: on a feed-kind-3 market an add waits for the clock second after its open. 6368 `BedrockFillOutsideWindow`: a fill or an exit settle landed before its target slot; send it at or after the target. **Wait for governance (`after-governance`).** 6367 `BedrockHalted`: the market is halted, so no price is read. New orders are refused, waiting orders are returned by their timeout, and settles wait. Only the config authority clears the halt: do not retry on a timer; read the market's terms and wait. **Change the request (`never`).** * 6346 `TakeProfitRaiseRefused`: a retarget may keep or narrow the take-profit target, never widen it (`0`, the payout cap, is the widest). * 6348 `AddPastEntryWordRange`: this feed-kind-3 position is too old to take an add. Open a new position. * 6349 `SessionFundDestinationRefused`: `session_fund` moves USDC only into the owner's own custody in a game the venue has enabled. Check the destination, the bumps and the game. * 6350 `LazerCommitShape`: a commit on feed kind 2, 3 or 4 is not in the allowed transaction shape. Rebuild it: [the commit's shape](/sdk/orders#the-commits-transaction-shape-feed-kinds-2-3-and-4). * 6352 `BedrockTermsMissing`: the market's terms account is not among the remaining accounts, or it is read-only where it must be writable. Add it: [on-chain oracle markets](/sdk/orders#on-chain-oracle-markets-feed-kind-4). * 6355 `BedrockProgramUnset`: the market has no oracle program set yet. It takes no order and reads no price until governance sets one. * 6356 to 6358 (`BedrockSegmentMissing`, `BedrockSegmentTooLong`, `BedrockFeedNotWritable`): the oracle accounts are wrong. The program account comes just before the feed, the feed is writable, the feed and its sources come last, and there are at most 17 of them. * 6359 `BedrockReturnMalformed`: the oracle program returned data the venue cannot read. Report it. * 6369 `BedrockGapParCloseOnly`: the position was open across a recorded gap in the oracle's prices. It closes at the last good price before the gap, with no fee, and no priced settle, stamp or retarget can reach it. * 6371 `BedrockStakeCapExceeded`: the side of the market is at its stake limit. Send a smaller stake, or open later. * 6372 `BedrockSessionEnding`: at the fill, the position would end after the market's session close. The order is returned by its timeout with the whole stake. Open with a shorter timer, or in the next session. * 6351, 6353, 6354, 6370 and 6373 are refusals of governance writes only. A client does not meet them. ### Exit log and game rounds (6377 to 6392) * 6377 `BedrockExitLogMissing` (do not retry): A feed-kind-4 read needs the market's exit log, writable. Add it. Anyone may build it (instruction 114). * 6378 `GameTermsInvalid` (do not retry): The game, the fee terms or the game slot is not valid. * 6379 `GameSlotBusy` (retry after the state changes): No fee-terms slot is free for the game terms. A slot frees when its open positions end. * 6380 `GameTermsTableRequired` (do not retry): This step on a game position needs the market's fee-terms account. Add it. * 6381 `KnockoutInsideWindow` (retry after the state changes): The proof is earlier than this position's game slot accepts. A later proof can land. * 6382 `GameAddRefused` (do not retry): A position on a game slot takes no add. * 6383 `GameMarketClosed` (retry after a governance write): This game is off on this market. * 6384 `GameOpenClosed` (retry after a governance write): Game opens are off. * 6385 `GameOpenCaller` (do not retry): This open is reachable only through the game's own program. * 6386 `GameLogRequired` (do not retry): A settle or void of a book with a result log must carry that log, writable. Add it. * 6387 `GameLogMismatch` (do not retry): The result log or the destination is not this book's. * 6388 `GameLogNotEmpty` (retry after the state changes): The book must be empty for this step. Wait for its positions and payouts to finish. * 6389 `GameBonusAboveLimit` (do not retry): The amount is above this book's limit. Lower it. * 6390 `GameBookNotProven` (do not retry): The signer is not the proven game owner of this book. * 6391 `GameValueAboveCeiling` (do not retry): A game setting is above its bound. * 6392 `GameOnlyMarket` (do not retry): This market does not take a new position or an add from this caller. Closing an open position still works. ### Referral links (6393) * 6393 `ReferralReferrerMissing` (do not retry): `set_referral` was asked to make the referrer's record, but the referrer wallet does not exist on chain. Check the address. A new referrer wallet must hold some SOL before it can be named. ### Classic Minute terms and the side cap (6394 to 6395) * 6394 `ClassicTermsUnavailable` (do not retry): a classic Minute round on a market with classic terms, and those terms cannot be frozen for this open. Pass the market's `FeeTermsTable` writable. If it already is, the market's setup is wrong and an operator must fix it. * 6395 `SideCoverCapReached` (retry later): this side of the market is full for the pool's size right now. The commit is voided at its fill and the whole stake comes back. Wait, take the other side, or use a smaller stake or a nearer target. ## Errors that are not the program's **Three** failure classes reach you that have nothing to do with the protocol. Conflating them sends people to debug the wrong thing, and the first one costs the most. > [accordion] The send you cannot confirm > > **You broadcast a transaction and could not determine its outcome.** This is not a refusal and > it is not a failure. It is the absence of an answer, and it is the class every client gets > wrong first. > > **A blockhash expiring bounds how long a transaction can be ACCEPTED for. It says nothing about > whether one already was.** So *"the blockhash expired, therefore nothing happened"* is not an > inference — it is a guess. > > **Three rules:** > > 1. **Look the signature up before you give up.** `getSignatureStatuses` searches only a node's > *recent status cache* and answers `null` for a signature that landed but has aged out — and > if your RPC pool races providers, `lastValidBlockHeight` can come from one node and > `getBlockHeight` from another further ahead, expiring your hash early. **Ask > `getTransaction`, which finds a signature wherever it is.** A hit at `confirmed` is > definitive. Unknown is the honest answer only when it IS the answer. > 2. **Say "unknown", never "nothing happened".** A client may say *refused*, it may say > *unknown*, and it may say *nothing moved* **only with a decoded program error code in > hand**. Carry the signature in the message so the trader can go and look. > 3. **Keep local state on an unknown.** Delete a session secret, clear a pending record or free > a nonce only on a decoded refusal. The branch where it landed is the expensive one — see > [sessions](/sdk/sessions). > > **And decode before you pattern-match the text.** A client that tests the error message for > `/reject|denied|cancel/i` before asking for the program error code can misread the program's > own words, because a program message may carry *refused* or *cancel* in plain use. A landed, fee-paying revert read that way > comes back to a trader as *"you declined it in your wallet"*, which is false. **Ask for the code > first.** A wallet decline can never carry one, because the wallet refuses before a transaction > exists. > [accordion] RPC failure > > `AllProvidersFailed` when every configured endpoint failed. With `readCached` you get the last > good value marked `stale` instead — render it with its age rather than showing a spinner that > never resolves. > [accordion] Composition failure > > `SenderRefusal` from the sender: the transaction could not be built or bound correctly. This is > a bug in the caller, or a quote that does not match what the program expects. It is not a > threshold and retrying does not help. ## The codes of the liquidity pool The liquidity pool has refusals of its own for the cover rule, the queue and the wind-down. They are in `catalogue()`, each with its retry class. On feed kind 2 your `open` is never refused for cover: the filler judges the cover rule at the fill and skips an order that does not fit (`CoverMarketFull` 6267, `CoverGlobalFull` 6268); the order stays pending, and the timeout return gives back the whole stake with no fee. On feed kinds 3 and 4 the cover is taken when the order lands, so the `open` or the `add_collateral` itself is refused with the same two codes, and nothing moves. Either way, show "try again when the pool has room". A transaction that lacks a capital account is a build error, and the SDK adds those accounts for you. ## Predict, do not discover The best error handling is the error you never raise. Most of the *Opening* table above is predicted by [`openGates`](/sdk/gates) before you spend a fee, with the value it measured and the threshold it was judged against, and most of the *Settling* table by `settleGates` and `settlePreview`. Neither report reads the guardian flags: read `config.oracleFrozen` and `config.settlesDisabled` yourself. > [!WARNING] > > **`MinimumHoldNotMet` (6103) is in the *Settling* table and neither report predicts it.** The > gate's only input is the position's opened slot, and neither `settleGates` nor `settlePreview` reads > that field. `settleGates` emits its own rows — market pin, fresh price, > exponent, reason legality, the position's frozen fee terms where it has any, outflow against > reserve, liquidator token — and none of them is the hold; `settlePreview`'s `voluntary` and `takeProfit` legality is the signer and the price, with no > slot term in it. A client that treats green gates as "the chain accepts it" meets 6103 on chain. > An add re-stamps the position's opened slot with the current slot, so a close within the hold of > an add meets it as well as one within the hold of the open. The *Adding* table's shared refusals are predicted by `addGates`, the report for an add. Use the catalogue for the cases you could not predict. Use the gates for everything else. # Reading gates Source: https://docs.rekt.money/sdk/gates Every refusal the program can raise, before you send — with the value it measured and the threshold it was judged against. This is the reason the SDK exists rather than a generated IDL client. A generated client lets you build a transaction and find out afterwards. `openGates` tells you **first**: every gate that can refuse the action, with its measured value and its threshold, in **the program's order for an open**. The guardian stops come first, the freeze and then the settle stop, and on a Minute book `MinuteDisabled` follows them. The table below lists them and the rest in that order. An open carries no quote, and the fill judges the price: see [the other gate reports](#the-other-gate-reports) and [orders and closes](/sdk/orders). > `CollateralOutOfRange` teaches nothing. > `stake $0.10 is below the minimum $0.20` teaches everything. ## What a gate is ```ts theme={"dark"} import { type Gate } from '@rekt-trading/1000x'; export function render(gate: Gate): string { return [ gate.ok ? 'PASS' : 'FAIL', gate.label, // a short name for the rule gate.value, // what was measured, already formatted for a human gate.threshold, // what it had to clear gate.error ?? '', // the ErrorCode name the program raises when this gate fails gate.detail, // one sentence on what this gate is protecting ].join(' '); } ``` > [!WARNING] > > **Never parse `value` back into a number.** `value` and `threshold` are strings formatted for a > reader. If you need a magnitude — for a progress bar, a colour, a chart — use `gate.scale`, which > carries `measured`, `limit` and a `headroom` from 0 to 1. Recovering `0.115` from `"11.5867 bp"` > means recomputing a protocol quantity in your presentation layer, which is exactly how an > interface and a chain come to disagree. `scale` is absent on categorical gates — paused or not, above the take-profit floor or below it — because a switch has no headroom and inventing one would put a half-full bar under a fact that is simply true or false. ```ts theme={"dark"} import { APPROACHING, approaching, headroom, type Gate } from '@rekt-trading/1000x'; export function bar(gate: Gate): { fill: number | null; warn: boolean } { return { // null on a categorical gate: draw a tick or a cross, not a bar. fill: headroom(gate), // Still passing, but inside the last APPROACHING of its room. Paint it. warn: approaching(gate), }; } export const warnBand = APPROACHING; ``` ## Building the context for an open `openGates` needs the state that the refusals are judged against. Everything in it is a read you already know how to do. ```ts theme={"dark"} import { Connection, PublicKey } from '@solana/web3.js'; import { INITIAL_POSITION_SLOTS, decodeTraderAccount, openGates, slotCapacity, traderPda, type ConfigView, type GateReport, type MarketView, type OpenRequest, type PriceReport, type TraderAccountView, type VaultView, } from '@rekt-trading/1000x'; export async function gatesForOpen( connection: Connection, state: { config: ConfigView; market: MarketView; vault: VaultView; price: PriceReport; nowUnix: bigint; }, owner: PublicKey, traderToken: PublicKey, req: OpenRequest, ): Promise { const traderAddress = traderPda(owner).address; const info = await connection.getAccountInfo(traderAddress, 'confirmed'); // `null` is a legitimate state: a trader who has never traded. It is not an error. const trader: TraderAccountView | null = info ? decodeTraderAccount(new Uint8Array(info.data)) : null; const balance = await connection.getTokenAccountBalance(traderToken, 'confirmed'); return openGates( { config: state.config, market: state.market, vault: state.vault, // The quotes the price report admitted, plus the ones it did not — pass what you read. The // price rows do not decide an order: the fill judges the price. quotes: state.price.admitted, trader, // The account's ALLOCATION, not the length of its position vector. They differ the moment // anything settles, and using the vector's length refuses opens the program would admit. slotCapacity: info ? slotCapacity(info.data.length) : INITIAL_POSITION_SLOTS, traderBalance: BigInt(balance.value.amount), nowUnix: state.nowUnix, }, req, ); } ``` > [!NOTE] > > `OpenRequest` is `{ budget: bigint; minCollateralOut: bigint; direction: 'long' | 'short'; rungBps: number; userTimerS: number; tier?: number }`. > `budget` is the most that leaves the wallet, and `minCollateralOut` is your floor on the stake it > buys; zero is refused. `rungBps` is basis points of stake — `20_000` is 2.00x, the floor — not a > whole multiple. Set `userTimerS` to `0` for no timer of your own, or to at least the venue's timer floor (26 seconds by default; read `config.timerFloorS`, where 0 means 26). > > **`tier` is optional and `0` or absent means the market's own.** Every live market sells 1000x, > so every open is 1000x: a lower tier is refused `LeverageBelowMinTier`, and a higher one > `LeverageAboveMarketTier`. Every distance a quote returns is `something / L`, so pass the same > `tier` to `openPreview` — it takes one as its seventh argument — or use `client.openGates`, which > threads the whole request through both. ## The refusals, in the order the program reaches them | Gate | Refuses with | | - | - | | the oracle is frozen by the guardian — not in `report.gates`; read `config.oracleFrozen` | `OracleFrozen` | | settles are disabled by the guardian — not in `report.gates`; read `config.settlesDisabled` | `SettlesDisabled` | | a Minute book opens on a market where Minute is off — not in `report.gates`; read `market.minuteEnabled` | `MinuteDisabled` | | protocol paused | `ProtocolPaused` | | market paused | `MarketPaused` | | the market's session calendar is shut, or less than a whole minimum tenor remains | `MarketClosed`, `SessionEndsBeforeTenor` | | inside a scheduled event window | `InsideEventWindow` | | user timer past the tenor | `TimerExceedsTenor` | | `minCollateralOut` left at zero | `MinCollateralOutRequired` | | collateral outside the governed bounds, or a budget above the ceiling | `CollateralOutOfRange`, `BudgetExceedsMaxCollateral` | | the budget buys less than the `minCollateralOut` you signed | `BudgetBelowCollateralFloor` | | leverage above the market's tier | `LeverageAboveMarketTier` | | leverage below the venue's floor for this market (every open is 1000x) — the floor is `min(config.minTier, market.tier)`, so resolve it against the market's own tier, never from `minTier` alone | `LeverageBelowMinTier` | | leverage the program does not offer | `RateOutOfRange` | | rung below the take-profit floor (2.00x) | `RungBelowFloor` | | rung above the payout cap | `RungAbovePayoutCap` | | a user timer below the venue's timer floor (26 seconds by default) — not in `report.gates`; send zero, or at least the floor | `TimerBelowFloor` | | the cover rule does not admit the fill — the filler skips the order, and the timeout return gives back the whole stake with no fee | none: a returned order is an outcome, not a refusal; not in `report.gates` | | this side of the market is at its stake limit — only where a market has a side limit set, and none has | `SideStakeCapReached` | | the trader has no free slot | `PositionSlotsFull` | Most of these are **states, not faults**. A frozen oracle, a paused market, a shut session, a market inside an event window, a pool at capacity and a trader whose book is full are all the protocol working. Show the sentence, not a stack trace — and see [error handling](/sdk/errors) for which ones retrying can ever fix. `openGates` also reports `open.balance` last, which is not a refusal of this program at all: it is the trader's SPL balance against the total debit, and the token program raises `SplInsufficientFunds`. It is in the report because a client that shows twelve green protocol gates and then fails on funds has explained nothing. > [!NOTE] > > **A market with no session calendar always passes the session row.** On a market that has one, > a position must be **dead** before the close, with the market's own settlement buffer to spare, so > no position is ever live while the market is shut. An open near the close is given a shorter > tenor rather than refused, until less than a whole minimum is left. `MarketClosed` means there is > no session open now; `SessionEndsBeforeTenor` means there is one, but not enough of it left. > > **`open.timer` comes before the collateral rows.** A timer past the tenor and a zero > `minCollateralOut` together are refused `TimerExceedsTenor`, which is the program's order. > [!WARNING] > > **`openGates` does not model a session key's own refusals — a second report does.** If > `authority` is a session key rather than the trader's own wallet, the program checks it right after > the first three rows of the table above and before the rest, and can > refuse with `DelegateExpired`, `DelegateWindowLimitReached`, `NotTheDelegate` or > `DelegateMayNotSign`. None of them appear in the table above or in `report.gates`. > > Call **`delegateGates(ctx, collateral)`** for those four, and **`sessionAllowanceGates(ctx, > debit)`** (the whole debit, never the stake alone) for the SPL token allowance — the one clock no account of this program can see, > and the one that ends most long sessions. A clean `openGates` report says nothing about either. > See [session keys](/sdk/sessions#gate-before-you-send) for the whole shape. ## Rendering the whole table Show every gate, not only the failure. A user who can see that every gate but one passes, and that the one still passing is close to binding, understands the system; a user who sees a single red error learns nothing. Render `report.gates` rather than a count of your own — the row set depends on the market (a single-feed market has no quorum row). ```ts theme={"dark"} import { approaching, headroom, type GateReport } from '@rekt-trading/1000x'; export function table(report: GateReport): string[] { return report.gates.map((g) => { const room = headroom(g); const mark = !g.ok ? 'x' : approaching(g) ? '!' : '.'; const pct = room === null ? '' : ` ${Math.round(room * 100)}% room`; return `${mark} ${g.label.padEnd(38)} ${g.value} / ${g.threshold}${pct}`; }); } ``` ## The other gate reports The same shape covers everything the program can refuse: | Function | Answers | | - | - | | `openGates(ctx, req)` | can this position be opened | | `addGates(ctx, req)` | can this position take this add | | `delegateGates(ctx, collateral)` | may this session key sign this open — owner, identity, expiry, spend window | | `sessionAllowanceGates(ctx, debit)` | is the SPL token allowance still large enough for the whole debit of this trade | | `settleGates(ctx)` | can this close be submitted, by this submitter, on this market | | `priceGates(quotes, market)` | is there an admissible price at all, and what is the median | | `sideRoom(direction, market, vault, vaultBalance)` | the stake a side can still take under a side limit, for a market that sets one | | `closableFromSlotOf(position, config, market)` | the first slot at which a close request can land, or `null` while there is none | Settlement's gates are covered in [settling a position](/sdk/settling); the two session reports in [session keys](/sdk/sessions). > [!NOTE] > > **An open and an add read no price.** The rows that judge a quote (`quote.*`, `price.*`) and the > forecast rows (`open.forecast`, `add.forecast`) do not refuse an order: the fill judges the first > price, and a price that fails returns the order. Pass `sideRoom` in the context, and `openGates` > and `addGates` add the side-limit row, which has nothing to judge while no market sets a limit. > [Orders and closes](/sdk/orders) has the rest. > [!NOTE] > > **`addGates` is the report for `add_collateral`.** An add takes `open`'s account list, `open`'s > entry fee and `open`'s side-limit rule, so it is refused by nearly everything `openGates` covers, plus its own rows: the position must be live and on this market, > the engine bounds the increment against the position's total after the blend, and `add.forecast` > compares the position's **remaining** life with the oracle's forecast of the close. ## Why this shape and not exceptions A refusal here is **data**, never a thrown string. Three reasons: * An interface renders several gates at once, and a user deliberately provoking one — trying a stake above the cap to see where the cap is — is the normal case, not the exceptional one. * The measured value is the whole explanation. An exception carrying only a name throws away the half of the message that helps. * Predicting the refusal client-side costs nothing and saves a transaction fee, a round trip, and a confusing failure at the worst moment. # Installation Source: https://docs.rekt.money/sdk/installation What the SDK needs to run, how it points at a cluster, and four rules to know before the first trade. Build against the SDK, not against a client generated from the IDL. The SDK has the settlement arithmetic, every refusal the program can raise *before* you send, and chain access that assumes providers fail. For a client in another language, write to [support@asymmetra.xyz](mailto:support@asymmetra.xyz). ## Requirements The SDK needs Node 20.19 or later, or Node 22.12 or later. It does not load on Node 20.18 or on 22.0 to 22.11. [Wheelman](/tools/wheelman), the bot built on it, needs Node 22.18 or later. `@solana/web3.js` is a **peer dependency** (`^1.98.0`): the SDK uses your copy rather than bundling its own. That matters: two copies of web3.js in one bundle means two `PublicKey` classes and `instanceof` checks that fail in ways that are painful to debug. > [!NOTE] > > The package is ESM-only; there is no CommonJS build. Your project needs `"type": "module"` in its > `package.json`, or `.mts` files. The setup and the install line are on the > [Quickstart](/sdk/quickstart#set-up). ## Point it at a cluster Two environment variables, referenced **by name only** — never paste an endpoint that carries a token into source, into a command line, or into a screenshot. | Variable | Used by | Shape | | - | - | - | | `SOLANA_RPC_URL` | your own `Connection` | a single endpoint | | `NEXT_PUBLIC_RPC_ENDPOINTS` | the SDK's pooled reader, `read()` / `readCached()` | comma-separated endpoints; unset, it reads the public Solana mainnet endpoint | ```ts theme={"dark"} import { Connection } from '@solana/web3.js'; const url = process.env['SOLANA_RPC_URL']; if (!url) throw new Error('SOLANA_RPC_URL is not set'); export const connection = new Connection(url, 'confirmed'); ``` Provider endpoints usually put the API key in the URL path, so a log line that prints the endpoint prints a live credential. Keep it in an environment file your version control ignores, and redact the path before you print anything. ### Reads that survive a provider outage If you set `NEXT_PUBLIC_RPC_ENDPOINTS`, the SDK's own reader races the two healthiest endpoints, demotes whichever fails, retries across *different* providers, and — with `readCached` — returns the last good value marked stale rather than throwing. ```ts theme={"dark"} import { readCached, AllProvidersFailed } from '@rekt-trading/1000x'; export async function currentSlot(): Promise<{ slot: number; stale: boolean }> { try { const hit = await readCached('slot', (c) => c.getSlot('confirmed'), 5_000); // Render the age. A number that is thirty seconds old and says so beats a spinner. return { slot: hit.value, stale: hit.stale }; } catch (e) { if (e instanceof AllProvidersFailed) throw new Error(`every RPC provider failed: ${e.message}`); throw e; } } ``` ## Four rules to know first > [accordion] 1. Money is bigint, in USDC base units > > Not `number`. A `u64` above `2^53` loses exactness as a double — silently, and rounding in a > direction nobody chose. Every amount in this SDK is a `bigint` in base units (six decimals), > and division truncates toward zero to match the on-chain engine exactly. > > Parse user input with `parseUsdc`, which is exact and never goes through a float: > > ```ts theme={"dark"} > import { parseUsdc } from '@rekt-trading/1000x'; > > export const oneDollar = parseUsdc('1.00'); // 1_000_000n > export const twentyCents = parseUsdc('0.20'); // 200_000n > ``` > [accordion] 2. Do not cache Params > > Every protocol parameter is **governed** and tunable on chain without a program upgrade. A > cached copy quotes stale terms to a user. Read them from the config account, and surface how > old your copy is rather than hiding it. > > `LAUNCH` holds the package's default values, and they are not the venue's. It is not a source > of truth: show nothing from it and settle nothing against it. > [accordion] 3. A slot index is not a position > > The one that costs a builder their *second* trade rather than their first. Positions live in > slots inside one trader account, and **slots are reused** — index 3 today and index 3 tomorrow > are different trades. > > So the SDK never hands you a bare index. The handle is > `PositionRef = { trader, slot, seq }`, and `settle` is called with `seq`, so a stale handle > finds nothing instead of closing a neighbour. > [accordion] 4. A landed open is an order, not a position > > **An `open` carries no quote.** It is an order: the stake is taken when it lands, and the venue's > next price after a short delay fills it or the order is returned. A wallet can sign it. Read the > entry when the order is filled, never at the tap: see [orders and closes](/sdk/orders). > > A quote matters only for the instructions that carry one, such as a `settle` a keeper sends. Its > age is judged **at execution**, against `market.maxOracleAgeSlots` slots of network time: a > governed field, so read it rather than assume it. Those are sent from code, not from a wallet > dialog; see [quotes and freshness](/sdk/quotes). A short-lived, scoped, revocable > [session-key delegate](/sdk/sessions) can sign the trades a person does make, with no prompt. And one that is not about the SDK at all: **at the barrier the trader receives nothing.** If your interface tells a user they keep a fraction of their stake on a knockout, it is wrong. ## Check the interface This is the shape of a first call against the SDK. It runs against nothing — no cluster, no keys — and reads only what the SDK derives locally or ships with: ```ts theme={"dark"} import { PROGRAM_ID, RUNG_FLOOR_BPS, catalogue, configPda } from '@rekt-trading/1000x'; export function selfTest(): string { const errors = catalogue(); // every refusal the program can raise, from the client IDL const config = configPda().address; // derived locally, never trusted from a web page return [ `program ${PROGRAM_ID}`, `config PDA ${config.toBase58()}`, `rung floor ${RUNG_FLOOR_BPS} bps`, `error catalogue ${errors.length} entries, codes ${errors[0]?.code} and up`, ].join('\n'); } ``` A live market's four preset rungs are not a constant: they end at the payout cap, which is governed. Read them with `presetRungsBps(rungCeilingBps(market, config.params))` once you have the config. ## Where to go next > [card] [Quickstart](/sdk/quickstart) > > Read the protocol, price an open, and see what every close would pay. > [card] [Session keys](/sdk/sessions) > > Who signs a trade, and how the program's session-key delegate works: authorise, fund, sign, > revoke. > [card] [Quotes and freshness](/sdk/quotes) > > What a quote is, why `6007` happens, and what to do instead of surfacing a failed trade. > [card] [Reading gates](/sdk/gates) > > Every refusal, before the action, with its measured value and its threshold. > [card] [Opening a position](/sdk/opening) > > Build the order, size it, simulate, send, and read its sequence number. > [card] [Error handling](/sdk/errors) > > What a client must handle, and when retrying helps. # Opening a position Source: https://docs.rekt.money/sdk/opening Build the order, size it, send it, and read its sequence number. An open carries no price: it takes the stake when it lands, and the venue's next price after a short delay fills it. **An `open` carries no price.** It takes the stake when it lands and becomes an **order**, and the venue's next price after a short delay fills it. [Orders and closes](/sdk/orders) has the rules, the timing settings, the events and the refusals. This page covers what building an open needs: the first-trade account, sizing, the instruction, sending it and the sequence number. ## The transaction shape An open is the `open` instruction and the compute-budget pair. There is no quote instruction and no price account, so a person can sign it in a wallet. ```text theme={"dark"} 0 ComputeBudget setComputeUnitLimit 1 ComputeBudget setComputeUnitPrice 2 open yours ``` > [!NOTE] > > **On a market of feed kind 2, 3 or 4 this shape is a rule, not a suggestion.** Only Compute Budget > instructions, and at most one each of `init_trader_account`, `set_referral`, `bind_referral` and > `mark_minute_trader`, may come before the `open`. Anything else before it is refused (`LazerCommitShape`, 6350), and so is a > second `open` in the same transaction. Instructions after the `open` are fine. See > [the commit's shape](/sdk/orders#the-commits-transaction-shape-feed-kinds-2-3-and-4). > [!WARNING] > > **Two hard walls, and both are refusals rather than warnings.** > > **1,232 bytes** (`PACKET_LIMIT_BYTES`). One packet. Measure the *signed* transaction, because the > signatures are part of the length: an estimate off the unsigned message understates it by 64 bytes > per signature. An open fits with room to spare. A session key adds about 128 bytes; see > [session keys](/sdk/sessions#the-byte-wall). > > **The declared compute budget.** `setComputeUnitLimit` bounds the whole transaction. Declare the > measured cost of the open, `computeUnitLimit('open')`, and simulate before you > send. An SDK release before the one that carries the current limits asks too little for a commit on > feed kind 3 or 4: see [compute limits](/sdk/orders#compute-limits). ## The first trade needs an account A trader's positions live in one account, the **book**. `open` does not create it: `initTraderAccount` does, as its own instruction, at the capacity you ask for (1 to 21 slots, or up to the venue's book capacity when you pass the `GovTable` as its last argument; `MAX_POSITION_SLOTS` (63) is the ceiling). The SDK sizes a new book at `DEFAULT_POSITION_SLOTS` (12), and `FRESH_TRADER_ACCOUNT_BYTES` is the matching account size. `initTraderAccount` and `open` fit in one transaction, so a first-time trader can sign once and pay the account's rent once, but you compose that transaction yourself. The recipe is [below](#create-and-trade-in-one-transaction). ```ts theme={"dark"} import { Connection, PublicKey } from '@solana/web3.js'; import { FRESH_TRADER_ACCOUNT_BYTES, rentExemptLamports, traderPda } from '@rekt-trading/1000x'; export async function accountCost( connection: Connection, owner: PublicKey, ): Promise<{ willCreate: boolean; rentLamports: bigint }> { const info = await connection.getAccountInfo(traderPda(owner).address, 'confirmed'); return info === null ? { willCreate: true, rentLamports: rentExemptLamports(FRESH_TRADER_ACCOUNT_BYTES) } : { willCreate: false, rentLamports: 0n }; } ``` The rent returns to **whoever paid it** when the book is closed, and the close destination is checked on chain, so a builder who sponsors accounts gets that capital back. ```ts theme={"dark"} import { ix, toHex, traderPda, vaultPda } from '@rekt-trading/1000x'; import { PublicKey } from '@solana/web3.js'; export function buildInit(args: { trader: PublicKey; payer: PublicKey; slots: number; vaultToken: PublicKey; payoutDestination: PublicKey; }) { return ix.initTraderAccount( { trader: toHex(args.trader), payer: toHex(args.payer), positions: toHex(traderPda(args.trader).address), vault: toHex(vaultPda().address), vault_token: toHex(args.vaultToken), // Where every settlement pays this trader. It must be a USDC account the trader owns, on the // vault's mint, and not frozen. payout_destination: toHex(args.payoutDestination), }, args.slots, // 1..=21 (more with the GovTable), default 12; resizeTraderAccount grows or shrinks the book later ); } ``` > [!NOTE] > > **`payoutDestination` is recorded on the book and every settlement pays that account.** The owner > can move it later with `setPayoutDestination`, signed by the owner alone; see > [reading positions](/sdk/positions#where-settlements-pay). If the account is later closed or > frozen, settlement still completes: the payout is held on the book and claimed with `claimPayout`. > [!NOTE] > > Need more room later? `resizeTraderAccount` grows or shrinks an existing book: up to 21 slots, or up to the venue's > book capacity when you pass the `GovTable` (`govTablePda()`) as its last argument, and > down to whatever still holds the trader's **live** positions (a shrink never discards an occupied > slot; it refuses instead). The **owner** and the book's recorded **rent payer** both sign it: the > rent payer funds a grow and receives the refund from a shrink. ### Create-and-trade in one transaction Put `initTraderAccount` before the `open`, and declare the sum of the two compute limits. A transaction that exceeds its declared limit is charged and reverted, so the prelude's own measured cost is added to the open's. ```ts theme={"dark"} import { ComputeBudgetProgram, type TransactionInstruction } from '@solana/web3.js'; import { computeUnitLimit, ourInstruction, type BuiltInstruction } from '@rekt-trading/1000x'; export function createAndOpen( prelude: BuiltInstruction, // the `initTraderAccount` trade: BuiltInstruction, // the `open` ): TransactionInstruction[] { const units = computeUnitLimit(trade.name) + computeUnitLimit(prelude.name); return [ ComputeBudgetProgram.setComputeUnitLimit({ units }), ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1_000 }), ourInstruction(prelude), ourInstruction(trade), ]; } ``` > [!WARNING] > > **If the two do not fit, send two transactions; do not refuse the trade.** Treat only the > packet-size refusal as the trigger for the two-transaction fallback. A failed **simulation** is not > one: retrying it in two pieces sends the failing half anyway, and the trader pays rent for a book > they are then refused the trade for. ## What the trader transfers **At most the `budget` you hand it.** `open` is fee-inclusive: you pass a total, the venue takes its entry fee from inside it and opens the largest position the remainder buys. The entry fee is `config.params.entryFeeBps`; at 0 the stake equals the budget. The number that leaves the wallet is never over the `budget` you sign. With an entry fee set it can undershoot by one base unit (floor rounding of the fee). A ledger reconciler should expect a gap of at most one base unit. Setting a user timer costs nothing extra. What you do still compute is the position the budget will buy, so you can set `min_collateral_out` (the floor below) and show the trader their size: ```ts theme={"dark"} import { sizeForTotal, parseUsdc, type ConfigView } from '@rekt-trading/1000x'; export function sizeFor(config: ConfigView, budgetText: string) { const budget = parseUsdc(budgetText); // exact; never through a float const size = sizeForTotal(budget, config.params); // the collateral this budget resolves to // Sign `budget` as the instruction's `budget`, and `size.collateral` as `min_collateral_out`. return { budget, collateral: size.collateral }; } ``` ## Sizing from a total the trader typed The trader names what leaves their wallet, you hand that number to the venue as `budget`, and the venue sizes the position inside it. `sizeForTotal` returns the collateral that budget resolves to, which is what you pass as `min_collateral_out`, and checks it against the governed collateral bounds. `collateralForTotal(total, entryFeeBps)` is the same inversion without the bounds check. ```ts theme={"dark"} import { sizeForTotal, type ConfigView } from '@rekt-trading/1000x'; export function sizeHalfDollar(config: ConfigView) { // Reads the live entry fee. At an entry fee of 0 the stake equals the budget. const size = sizeForTotal(500_000n, config.params); // size.collateral 500000n the position the budget buys; pass it as `min_collateral_out` // size.debit 500000n what leaves the wallet (at most the budget you sign) // size.dust 0n what the budget could not spend // size.summary "$0.50 buys a $0.50 stake and costs exactly $0.50." // size.refusal null or a Gate-shaped refusal naming the bound that was missed return size; } ``` > [!WARNING] > > **Some totals cannot be hit exactly, and the SDK says so rather than rounding.** When an entry fee > is set it truncates, so the debit steps by one *or two* base units as the stake increments, and for > some totals no stake has a debit equal to them. `collateral` is always the largest stake that fits > and `dust` is the remainder, never negative. At an entry fee of 0, `dust` is 0. > > Show the dust. `summary` states all three figures at the precision they need: a two-decimal > currency formatter renders a $0.099999 charge as `$0.10\`. `refusal` is a [`Gate`](/sdk/reference): same fields, same `error`, so an interface that already draws the open gate report draws this with no new code. It carries two extra values: `bound`, the governed limit that was missed, and `boundTotal`, the total that buys exactly that bound and is therefore the correction to offer. **The stake is never clamped to the bound**: a total that buys more than the maximum collateral reports what it really buys and refuses, as the chain does with `BudgetExceedsMaxCollateral`. ## Build the instruction Every account the program needs, addressed by name, with the market's remaining accounts appended. Addresses are passed as hex: `toHex` converts a `PublicKey`, `toBase58` goes back. ```ts theme={"dark"} import { PublicKey } from '@solana/web3.js'; import { assetId, configPda, ix, marketPda, priceAccountsFor, toHex, traderPda, vaultPda, type BuiltInstruction, type ConfigView, type MarketView, } from '@rekt-trading/1000x'; export function buildOpen(args: { /** The decoded config, read for this request. */ config: ConfigView; symbol: string; market: MarketView; trader: PublicKey; traderToken: PublicKey; vaultToken: PublicKey; protocolToken: PublicKey; /** The fee-inclusive TOTAL to spend. The venue takes its fee from inside it. */ budget: bigint; direction: 'long' | 'short'; /** The optional take-profit target in bps of stake: at least 20_000 (2.00x). `0` means no target other than the payout cap. */ rungBps: number; userTimerS: number; /** The floor on the position SIZE: `sizeForTotal(budget, config.params).collateral`. */ minCollateralOut: bigint; /** A durable key you choose, or `0n`. Read by nothing on chain. */ openerTag: bigint; }): BuiltInstruction { return ix.open( { // Whoever SIGNS: the trader, or a session key they authorised. The owner is read from // `positions`, so there is no separate trader account. authority: toHex(args.trader), trader_token: toHex(args.traderToken), config: toHex(configPda().address), market: toHex(marketPda(assetId(args.symbol)).address), vault: toHex(vaultPda().address), vault_token: toHex(args.vaultToken), protocol_token: toHex(args.protocolToken), positions: toHex(traderPda(args.trader).address), // null for a wallet-signed open. Pass `delegatePda(owner).address` when a session key signs. delegate: null, }, { // The fee-inclusive total. The debit is AT MOST this. budget: args.budget, direction: args.direction === 'long' ? 0 : 1, // Basis points of stake, not a whole multiple: 20_000 is 2.00x, the floor. A bare `2` asks // for 2 bps and is refused as `RungBelowFloor`. rung_bps: args.rungBps, user_timer_s: args.userTimerS, // The trader's MANDATORY floor on the position SIZE. A fee rise between quote and execution // then reverts instead of shrinking the position. `0n` is refused (`MinCollateralOutRequired`). min_collateral_out: args.minCollateralOut, // Pass `null`. The field is carried in the `PositionOpened` event and drives nothing else. referrer: null, // The leverage to open at; `0` means the market's own tier, 1000x on every market. Pass `0`. // A value above the market's tier is `LeverageAboveMarketTier`; a value below the floor, // `min(config.minTier, market.tier)`, is `LeverageBelowMinTier`. Every open is 1000x. tier: 0, // A durable key YOU choose, written onto the position and read by nothing on chain. // `(trader, seq)` does not survive a `closeTraderAccount`, so key your own records off this. opener_tag: args.openerTag, }, // The remaining accounts of an open: the governance table on a feed-kind-3 market (the program // refuses a kind-3 open without it), then the market's fee-terms account when it has terms. // An order carries no quote on either kind. Never `market.feeds`. Always include the fee-terms // account: an open without it is accepted but freezes the legal maximum as its exit-fee bound // and runs no rung check. priceAccountsFor(args.market, args.config, 'open'), ); } ``` > [!NOTE] > > **The rung is basis points of stake, not a whole multiple.** `20_000` is 2.00x, the floor below > which the protocol will not price a take-profit, and the ceiling is the payout cap. Any rung > between the two is admitted. For four preset buttons that always end at the ceiling, use > `presetRungsBps(rungCeilingBps(market, config.params))`. > [!WARNING] > > **`min_collateral_out` protects against a number the CALLER chose.** Set it to the collateral you > predicted, `sizeForTotal(budget, config.params).collateral`, never a token value. A client that > passes `1` satisfies the check and is protected by nothing: a fee rise between quote and execution > would shrink the position silently instead of reverting. `0n` is refused outright > (`MinCollateralOutRequired`). There is no debit ceiling to compute: the debit is bounded by > `budget`. ## Who signs An open carries no quote, so a person can approve it in a wallet. After a timeout, never sign a second open for the same intent inside one blockhash life. Send the same signed bytes again. A [session key](/sdk/sessions) saves the wallet prompt on every trade. Two arguments on this page are the whole of it: * **`authority`** is whoever signs: the trader's own wallet, or their session key. * **`delegate`** is `null` for a wallet-signed open, and the session's account (`delegatePda(owner).address`) when the session signs. Passing `null` with a signer who is not the owner is refused by the program, so this cannot open against someone else's book. ## Simulate, then send Simulate first: it costs nothing and returns a refusal as a name. Send only when the simulation is clean. ```ts theme={"dark"} import { ComputeBudgetProgram, Connection, Keypair, TransactionMessage, VersionedTransaction, } from '@solana/web3.js'; import { computeUnitLimit, errorForCode, ourInstruction, programErrorCode, type BuiltInstruction, } from '@rekt-trading/1000x'; export async function sendOpen(args: { connection: Connection; payer: Keypair; built: BuiltInstruction; /** Leave true until you have watched this path work. It sends nothing. */ dryRun: boolean; }): Promise { const { blockhash, lastValidBlockHeight } = await args.connection.getLatestBlockhash('confirmed'); const message = new TransactionMessage({ payerKey: args.payer.publicKey, recentBlockhash: blockhash, instructions: [ ComputeBudgetProgram.setComputeUnitLimit({ units: computeUnitLimit('open') }), ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1_000 }), ourInstruction(args.built), ], }).compileToV0Message(); const tx = new VersionedTransaction(message); tx.sign([args.payer]); const sim = await args.connection.simulateTransaction(tx, { commitment: 'confirmed' }); if (sim.value.err !== null) { // A refusal is data: the name, the cause, the fix and whether retrying can ever help. const refusal = errorForCode(programErrorCode(sim.value.err) ?? -1); throw new Error(refusal ? `${refusal.name} (${refusal.retryable}): ${refusal.fix}` : JSON.stringify(sim.value.err)); } if (args.dryRun) return null; const signature = await args.connection.sendTransaction(tx); const done = await args.connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed'); if (done.value.err !== null) throw new Error(`reverted: ${signature}`); return signature; } ``` > [!NOTE] > > **`dryRun: true` is the posture to default to.** It builds and signs exactly what would be sent, > simulates it and stops. It is safe against mainnet and spends nothing. ## What comes back `open` returns the position's **sequence number** as Solana *return data*: the per-transaction buffer, not an account you have to read. Eight little-endian bytes, no extra transaction bytes, no extra account, no extra signature. It also emits a `PositionOpened` event carrying the same number. That number names an **order**. `PositionOpened` has no price field, and the position's `entryPrice` is 0 until a filler writes it: read the entry from `EntryFilled`, or watch the book until the phase leaves `PendingOpen`. See [orders and closes](/sdk/orders#opening-an-order-then-a-fill). **Read the sequence number from the landed transaction's logs.** `landedOpenedSeq` reads the `PositionOpened` event for your book and market, and the return value that same open logged, and refuses if any two witnesses disagree. Pass the **book owner**, not the signer: a session key signs for the owner's book, and an open made through Minute is on Minute's book. When no `PositionOpened` in the transaction names that owner on that market, the answer is `seq: null`, and the logged return value is not read. Two opens for two books or two markets in one transaction each read their own. ```ts theme={"dark"} import { landedOpenedSeq, toHex } from '@rekt-trading/1000x'; import type { Connection, PublicKey } from '@solana/web3.js'; export async function mintedSeq( connection: Connection, signature: string, owner: PublicKey, market: PublicKey, ): Promise { const landed = await connection.getTransaction(signature, { commitment: 'confirmed', maxSupportedTransactionVersion: 0, }); const minted = landedOpenedSeq({ logs: landed?.meta?.logMessages ?? null, returnData: null, owner: toHex(owner), market: toHex(market), }); if (minted.seq === null) { // Nothing was guessed. `why` says what the transaction did not carry. console.warn(minted.why); } return minted.seq; } ``` `seq`, with the owner and the slot, is the handle: ```text theme={"dark"} PositionRef = { trader, slot, seq } ``` Hold the `seq`. Never hold the bare slot index: slots are reused, and `settle` addresses by `seq`, so a stale handle finds nothing instead of closing somebody's live position. > [!WARNING] > > **Send one `open` per transaction if you intend to read the sequence back.** Two `open`s for the > same book and market in one transaction emit two `PositionOpened` events, and `landedOpenedSeq` > refuses rather than naming one. If the transaction cannot say (`seq: null`), read the trader account and match on the market and the opened slot. That read is exact but it is a second round trip, and it is a snapshot: anything that settled in between has already left the book. Never take the largest live sequence as the answer. Next: [reading positions](/sdk/positions). ## If it is refused Every refusal you can meet here is named, with a cause, a fix, and whether retrying can ever help. See [error handling](/sdk/errors). The common ones on an open are a market that is paused or closed and a stake outside the governed bounds. All of them are states rather than faults, and [`openGates`](/sdk/gates) predicts the ones it models before you spend a fee finding out. It does not model the guardian's oracle freeze (`OracleFrozen`, read `config.oracleFrozen`). An order that lands can still be **returned** (`OpenVoided`). When the pool cannot cover it, the fill does not happen, and anyone returns the order when the fill window ends. That is not a refusal, and the stake comes back whole. The price checks and the cover rule decide at the fill, not at the open. # Orders and closes Source: https://docs.rekt.money/sdk/orders An open and a double-down are orders: the stake is taken when the order lands, and the venue's next price fills it. A close is a request that anyone completes. The rules a client or a bot builds against, the events that report each step, and the refusals. An `open` and an `add_collateral` carry no price. Each one takes the stake when it lands and becomes an **order** that waits for the venue's next price. A close is a **request** that carries no price, and anyone may complete it with a priced `settle`. This page is the contract a client or a bot builds against. A bot that opens, adds and requests closes needs a wallet and an RPC endpoint. It needs no access to the price feed, no token and no key from us. Only `settle`, `stamp_book`, `set_take_profit` and `prove_price` carry a quote: see [getting prices](/sdk/prices). > [!NOTE] > > **Build an open with `ix.open(accounts, args, priceAccountsFor(market, config, 'open'))`**, as > [opening a position](/sdk/opening#build-the-instruction) shows, an add with > `addCollateralFor(market, config, accounts, args)` and a close request with > `requestCloseFor(market, accounts, seq)`. Each reads the market's feed kind and the governed > `config`: decode both on every request. On a feed-kind-3 market (`isKind3Market(market)`) the open, > the add and the close request each carry the governance table, and the program refuses them > without it (`GovTableRequired`). These three add it. Never build an open with `openForMode`: it > leaves out the market's fee-terms account and the governance table. A market of feed kind 4 (an > on-chain oracle market, `market.feedKind[0]` is 4) has its own account list: see > [on-chain oracle markets](#on-chain-oracle-markets-feed-kind-4). ## The life of a position An open lands as an order. A fill makes it a live position, or the order is returned with the whole stake. A live position ends at a close request, its barrier, its target or a timer, and a settle closes it. [How a position ends](/how-it-works#how-a-position-ends) has every close reason, and the [glossary](/glossary) has the words. ```mermaid theme={"dark"} flowchart LR commit["open lands: an order"] -->|filled| live["live position"] commit -->|"not filled in the fill window"| returned["returned: the whole stake comes back"] live -->|close requested| settled["settled"] live -->|barrier touched| settled live -->|target reached| settled live -->|timer ends| settled ``` ## The timing settings Every wait on this page is a count of slots, and every count is a governed setting. Read them through the SDK on each request. Do not compile one into a client. | Setting | What it sets | Read it | | - | - | - | | `d` | The delay from an order, an add, a close request or an expiry mark to its **target slot** | `timing.d` | | `T_q` | The latest slot after the target at which the first price can still fill an order or an add | `timing.tQ` | | `T_fill` | The slots after the target in which a filler can fill. After them, anyone can return the order | `timing.tFill`, and `fillDeadlineSlots(timing)` for `d + T_fill` from the order | | `W` | The exit window: the slots in which one price prices a requested or marked exit | `timing.wExit`, and `exitWindowSlots(timing)` for `d + W` from the request | | `W_ko` | How old a price can be and still prove a knockout or a take-profit | `timing.wKo` | | `M_add` | The slots after a filled double-down's price in which the position is held | `timing.mAdd`, and the copy on the position (`addMemo(position)`) | Each setting can change by a governed write with no program upgrade. The SDK is the source: ```ts theme={"dark"} import { Connection } from '@solana/web3.js'; import { configPda, decodeConfig, decodeGovTable, exitWindowSlots, fillDeadlineSlots, govTablePda, timingInForce, } from '@rekt-trading/1000x'; export async function readTiming(connection: Connection) { const infos = await connection.getMultipleAccountsInfo( [configPda().address, govTablePda().address], 'confirmed', ); const configInfo = infos[0] ?? null; const govInfo = infos[1] ?? null; if (configInfo === null) throw new Error('the config account is missing'); const config = decodeConfig(new Uint8Array(configInfo.data)); const gov = govInfo === null ? null : decodeGovTable(new Uint8Array(govInfo.data)); // `null` for a setting that is not in force. There is no default: do not invent one. const timing = timingInForce(config, gov); return { config, timing, fillDeadline: fillDeadlineSlots(timing), // d + T_fill, from the slot the order landed in firstExitWindowEnds: exitWindowSlots(timing), // d + W, from the slot the request landed in }; } ``` ## Opening: an order, then a fill 1. **Send `open`.** It carries no quote. On a feed-kind-3 market its remaining accounts are the governance table, the Instructions sysvar and the venue's capital account (writable), then the market's fee-terms account when the market has terms (`priceAccountsFor(market, config, 'open')` builds the list, and `ix.open` marks the capital account writable). The transaction must also have [the commit's shape](#the-commits-transaction-shape-feed-kinds-2-3-and-4). When it lands, the stake is taken, the slot holds the order with `entryPrice` 0, and `PositionOpened` carries the sequence number. It is an order, not yet a position. 2. **The entry price is the first price of the venue's price feed at or after `d` slots from the slot in which the `open` landed.** On a feed-kind-3 market the delay is clock time from the second the `open` landed, and the entry is the first signed tick at or after it. A listed filler writes it. Read it from the event `EntryFilled` (`entryPrice`, `quoteSlot`), or from a non-zero `entryPrice` on your own book. On a feed-kind-3 market `quoteSlot` is the slot the fill landed in. 3. **Or the order is returned.** The event is `OpenVoided`: `cause`, `refundTotal`, `feeKept` and `delivered`. An order is returned when the first price came too late or did not meet the venue's quality rule, when the market closed, or when nothing filled it inside `d + T_fill` slots of the order (for example, on feed kind 2, when the pool could not cover it). `refundTotal` is the whole stake, and `feeKept` reads 0. `delivered` false means the payout destination could not receive the refund, and it is held on the book: claim it with `claimPayout`. 4. **You cannot fill your own order** (`NotAListedFiller`, 6205). You need not return it either: after `d + T_fill` slots anyone may send `void_open`, and the venue's keepers do. | `cause` | What it means | | - | - | | 1 | The price came late. | | 2, 3, 4 | The price did not meet the venue's quality rule. | | 5, 6 | The market is closed or about to close. | | 7 | Not filled in time, including an order the pool could not cover. | **On feed kinds 3 and 4 the pool's cover is taken when the order lands.** An order the pool cannot cover is refused at once (`CoverMarketFull`, 6267, or `CoverGlobalFull`, 6268), and nothing moves. A returned order gives its cover back. On feed kind 2 the cover is judged at the fill, as above. `voidReasonOf(cause)` names the cause, and `VOID_REASON_TEXT` has the words for a trader. The fill is the step that judges the price. So the price rows of `openGates` do not decide an order, and the quote refusals of [quotes and freshness](/sdk/quotes#related-refusals) cannot refuse one. Build with `ix.open` and `priceAccountsFor(market, config, 'open')`, send, and then watch the book. The `EntryFilled` or `OpenVoided` event is in the filler's or the keeper's transaction, not in yours: ```ts theme={"dark"} import { Connection, PublicKey } from '@solana/web3.js'; import { decodeTraderAccount, findBySeq, phase, traderPda, type Phase } from '@rekt-trading/1000x'; /** Where an order stands: 'PendingOpen' until the fill, then the position's phase, or 'gone'. */ export async function orderState( connection: Connection, owner: PublicKey, seq: bigint, ): Promise { const [info, nowSlot] = await Promise.all([ connection.getAccountInfo(traderPda(owner).address, 'confirmed'), connection.getSlot('confirmed'), ]); if (info === null) return 'gone'; const position = findBySeq(decodeTraderAccount(new Uint8Array(info.data)), seq); // Gone: returned (`OpenVoided`) or already settled. The events say which. if (position === null) return 'gone'; // After the fill, `position.entryPrice` is the entry and `position.openedSlot` its slot. return phase(position, nowSlot); } ``` ## Doubling down Send `add_collateral` with no quote. `CollateralCommitted` is in your own transaction: the added stake is taken (`addedCollateral`, `totalDebit`), the timer extension is written at once (`timerAfterS`), and `addTarget` is the slot `d` after the add. Then one of two: * **`CollateralAdded`.** A filler priced the add at the first price at or after `addTarget`. It carries the new entry (`entryPrice`) and the entry before it (`entryPriceBefore`). * **`AddReversed`.** The added stake is returned in full (`refundTotal`), as for a returned order. `cause` is one of the open's causes, or 8 (the price was outside the position's limits: at the add's price the position was already at its barrier or its target) or 9 (the position was knocked out first). Rules a client must handle: * **Until one of the two arrives, and then for `M_add` slots after the price of a filled add**, a close request, a retarget, an expiry mark and a second add return `AddPending` (6211). `closableFromSlotOf` includes that time. * **A reversed add keeps the time it added to the timer.** Its stake comes back. * **A knockout price from before the add still counts in that time.** A price that breached the barrier of the entry in force at its slot can still prove the knockout. `KnockoutBeforeAdd` reports it, the position is knocked out on its old stake, and the added stake comes back (`AddReversed`, cause 9). * **A touch of the take-profit target while an add waits for its price cannot be stamped**, and it is lost if the add is then filled. * `addCollateralFor` refuses to build an add while adds are off (`AddsDisabled`, 6212). On a feed-kind-3 market the add carries the governance table: build it with `addCollateralFor`, not `addCollateralForMode`, which refuses a kind-3 list. ## Closing: a request, then a settle 1. **Send `request_close`**, signed by the owner or a session key. It carries no quote, so it cannot fail on a stale price. On a feed-kind-3 market it carries the governance table (`requestCloseFor` adds it). `CloseRequested.exitTarget` is the slot `d` after the request; on a feed-kind-3 market it reads 0, because that market's exit target is a clock second, not a slot. 2. **The exit price is the first price of the venue's price feed at or after `exitTarget`.** The close is done when `SettlementPriced` and `SettlementReceipt` arrive. 3. **Anyone may send that settle, and the venue's keepers do.** `isPermissionless('voluntary', phase)` is true once the phase is `ExitRequested`. 4. **The window rule.** If nobody settles inside `W` slots of the target, the price becomes the first price of the next window of `W` slots, and so on. `SettlementReceipt.window` is the count of windows that rolled: 0 for a close settled in its first window. 5. **A request cannot be withdrawn.** A second request returns `ExitPending` (6213): treat it as success. 6. **`SettlementPriced.unverified` reads `true` while a market lists one price feed.** A price from a single feed is `unverified` by construction; it does not mean the price was wrong. Do not show a warning or a badge from it. > [!WARNING] > > **Never show "your close price is locked".** Until the settle lands, the next window's price can > apply, and a knockout price in between counts. ```ts theme={"dark"} import { PublicKey } from '@solana/web3.js'; import { assetId, configPda, marketPda, requestCloseFor, toHex, traderPda, type MarketView } from '@rekt-trading/1000x'; export function buildRequestClose(args: { /** The decoded market of the position: its feed kind decides whether the governance table rides along. */ market: MarketView; owner: PublicKey; /** The owner, or a session key they authorised. */ signer: PublicKey; /** `delegatePda(owner).address` when a session key signs, else null. */ delegate: PublicKey | null; symbol: string; seq: bigint; }) { return requestCloseFor( args.market, { authority: toHex(args.signer), config: toHex(configPda().address), // The position's own market: it carries the market's hold. market: toHex(marketPda(assetId(args.symbol)).address), positions: toHex(traderPda(args.owner).address), delegate: args.delegate === null ? null : toHex(args.delegate), }, args.seq, ); } ``` `request_close`, `mark_expiry` and `open` need no quote instruction: send each one with the compute-budget pair. `computeUnitLimit(built.name)` gives the declared limit, and for the open `computeUnitLimit('open')`. ## The minimum hold A position cannot be closed by its owner in the first slots after its entry price. * The venue has one hold for every market: `resolveMinHoldSlots(config.minHoldSlots)`. A market can have a longer one: `market.closeHoldSlots` (0 is none). The hold in force is the larger of the two (`holdInForce`). * It counts from the entry price: `EntryFilled.quoteSlot`, and after a filled double-down from the add's price, which is the position's `openedSlot` on the book. * A close request inside it returns `MinimumHoldNotMet` (6103) for the venue's hold or `MarketHoldNotMet` (6236) for the market's. Neither one is a failure of the position. * **"Can close in N seconds", with no guess:** `closableFromSlotOf(position, config, market)` is the first slot at which a request can land, from three public accounts. It is `null` while the position is an order or an add waits. `slotsUntil(slot, nowSlot)` counts the slots, and `estimatedSecondsUntil(slots, slotMs)` turns them into an estimate that you label as one. Pass a slot time you measured (`getRecentPerformanceSamples`), not `config.params.slotMs`, which is longer than a mainnet slot. * The request must land at or after that slot. * A take-profit proof must also clear both holds, on the slot of its own price. * A knockout is never held back. A market's own hold never holds back a timer end. ## Timers * From the deadline, anyone may send `mark_expiry` with reason 3 (`userExpiry`) or 4 (`tenorExpiry`). `ExpiryMarked.exitTarget` is the slot `d` after the mark, and the exit price is the first price at or after it, by the same window rule as a close. * A settle with an expiry reason on a position that has no exit target returns `ExitNotAnchored` (6214): mark it first. * A wrapper such as Minute sends the mark and then its own settle from slot `exitTarget` on: two transactions, at least `d` slots apart. * A timer is 0 or at least the venue's **timer floor** at the open. After an add, the position's deadline must be at least the timer floor after the add lands (`TimerBelowFloor`, 6225). * The timer floor is a governed setting. A stored 0 means the default, 26 seconds. A governed write can set it from 10 to 26 seconds, and never below what the venue's timing settings need. Read `config.timerFloorS` from `decodeConfig` on each request, and resolve 0 to 26. * On a feed-kind-4 market a timer must also end after the order's fill window: see [on-chain oracle markets](#on-chain-oracle-markets-feed-kind-4). ## Knockouts and take-profits * **Anyone may prove a level with any signed price that is newer than the entry and at most `W_ko` slots old.** So a position can be knocked out by a price up to `W_ko` slots old. * After a close request or an expiry mark, only a price that is not later than the exit price can prove a level (`ExitPending` otherwise). * While an add waits for its price, a touch of the take-profit target cannot be stamped, and it is lost if the add is then filled. * After a take-profit retarget, only a price at least `d` slots after the retarget proves the new target (`TakeProfitProofTooEarly`, 6220). * **A retarget keeps or narrows the take-profit target. It never widens it.** `set_take_profit` with a `rung_bps` above the position's current target is refused (`TakeProfitRaiseRefused`, 6346). A target of 0 means the payout cap, the widest target, so a position with a target cannot move to 0\. To get a wider target, open a new position. * `stamp_book` records the level on the book; the settle that pays it follows. It is the only stamp that can prove a knockout with a price from before a filled double-down. ## The commit's transaction shape (feed kinds 2, 3 and 4) An `open` or an `add_collateral` on a market of feed kind 2, 3 or 4 is a **commit**, and the venue refuses a commit in any other transaction shape (`LazerCommitShape`, 6350). The venue reads the shape from the Instructions sysvar, so the sysvar is one of the commit's remaining accounts. * **The commit is a top-level instruction of the venue**, or it runs inside Minute's `open_round`, `double_down`, `open_round_session` or `double_down_session`, called directly by that top-level instruction. No other program may call it. * **Before the commit's top-level instruction, only these may come:** Compute Budget instructions, and at most one each of `init_trader_account`, `set_referral`, `bind_referral` and `mark_minute_trader` (the venue's), and Minute's `init_player`. Nothing else: no memo, no transfer, no second commit. * **After it, anything may come.** Wallet guards that a wallet appends after the trade are fine. * One commit per transaction. How a client complies: 1. Put the Compute Budget pair first. Then, on a first trade only, `init_trader_account` and the referral link. Then the `open` or the `add_collateral`. 2. Build the remaining accounts with `priceAccountsFor(market, config, 'open')` or `addCollateralFor(...)`. They carry the Instructions sysvar and the capital account, and on feed kind 3 the governance table. A signature-check instruction before the commit is refused, on feed kind 2 too: a commit reads no price. 3. Put any other instruction of yours in a separate transaction, or after the commit. A transaction refused with 6350 moves no USDC. If it lands it still pays its network fee. Rebuild it in the shape above and send it again. ## On-chain oracle markets (feed kind 4) A market of feed kind 4 (`market.feedKind[0]` is 4) reads its price from an on-chain oracle program, inside the venue's own instruction. There is no quote and no signed message to fetch. The venue's keepers fill, settle and stamp these markets. A client opens, adds and requests a close. **Each market has its own terms account**, the PDA of `["bedrock_terms", market]` under the venue program. It holds the market's delays and limits. Read it before you show timing for the market. | Term | What it sets | | - | - | | Entry delay, in slots | The target slot of an order or an add: the slot the commit landed in, plus the delay | | Fill window, in slots | The slots after the target in which anyone may fill. After them, anyone may return the order, and the whole stake comes back | | Exit delay, in slots | The target slot of a close request: the request's slot plus the delay. Never shorter than the entry delay | | Retarget delay, in slots | After a take-profit retarget, the first slot at which a price proves the new target. Never shorter than the exit delay | | Maximum price age, in slots | The oldest price the venue accepts | | Stake limit per side | The most stake one side of the market may hold. 0 is no limit | | Halt | While set, the market takes no order, and no fill, stamp or priced settle runs | **Opening and adding.** The commit carries the same list as a kind-3 commit, then the market's terms account (read-only), then the fee-terms account when the market has terms: ```text theme={"dark"} remaining accounts of open and add_collateral on feed kind 4: governance table read-only Instructions sysvar read-only capital account writable the market's terms account read-only fee-terms account read-only, only when the market has terms ``` The transaction must have [the commit's shape](#the-commits-transaction-shape-feed-kinds-2-3-and-4). `addCollateralFor(market, config, accounts, args)` builds an add with this list. The cover is taken at the commit, as on kind 3. **The fill.** The entry price is the oracle's price in the slot the fill lands in, at or after the target slot and inside the fill window. Anyone may fill. If no fill lands in the window, the order is returned with the whole stake and no fee. A fill that would leave the position ending after the market's session close is refused, and the order is returned the same way. **A timer must end after the fill window.** At the commit, `(entry delay + fill window)` slots, converted at the venue's slot time, plus one second, must fit inside the position's timer. A shorter timer is refused with `TimerBelowFloor` (6225). **Closing.** `request_close` carries the market's terms account (read-only). `requestCloseFor` adds it. The exit price is the oracle's price in the slot the settle lands in, at or after the exit target. **Settles, stamps and fills that you send yourself.** Every instruction that reads a price ends with the oracle accounts, **last**, in this order: ```text theme={"dark"} ...the instruction's own remaining accounts (books, capital riders, fee-terms account, ...) governance table read-only the market's terms account writable the oracle program the oracle feed writable (market.feeds[0]) the feed's sources in the feed's stored order, at most 16 ``` Nothing of the venue's may come after the feed. The venue finds the feed by its address, so the account just before it must be the oracle program the market's terms name. **When the oracle has no price.** A fill waits for the next slot that has one. A settle waits. A position that was open across a recorded gap in the oracle's prices closes at the last good price before the gap, with no fee, and anyone may send that close. When no price before the gap is known, the position waits for the venue's 24-hour refund at par. **The guardian can halt one market.** While it is halted, new orders are refused (`BedrockHalted`, 6367\), an order waiting for a fill is returned by its timeout with the whole stake, and settles wait. ## Compute limits Declare the measured limit of each instruction, `computeUnitLimit(built.name)`, and simulate before you send. Each limit is the instruction's measured cost plus 15 % and a small margin, rounded up to a thousand. A transaction that passes its declared limit is charged and reverted. * **A commit on feed kind 3 or 4** (an `open` or an `add_collateral`) takes the pool's cover, so it costs more than a kind-2 commit. `computeUnitLimit('open')` and `computeUnitLimit('add_collateral')` cover the dearest shape, a session key on a market with fee terms. * **An instruction that reads an on-chain oracle price** (feed kind 4) also runs the oracle program. Add one oracle read to its limit: `computeUnitLimit('settle', { bedrockRead: true })`. A batch fill makes one read, not one per entry. * **A settle** declares `computeUnitLimit('settle')`, 51,000, for the ordinary shape. A dearer shape (a book with a result log, a kind-3 anchored position, a ratio market, a kind-4 read) takes `settleComputeUnitLimit(shape)`; `settleComputeUnitLimit()` with no shape is the largest of them. * **Loaded account data.** If you set a loaded-accounts data limit at all, leave at least 4 MB above the venue's own accounts on a feed-kind-4 instruction that reads a price. If you do not set one, the default is enough. ## Settling or stamping for others This is optional. The venue's keepers send settles and stamps. * A settle of a requested or marked exit needs the **window quote**: the first price of the venue's price feed at or after the start of the current window, `exitTarget + K × W`, where `K` is the count of whole windows since the target. Any other quote returns `NotWindowQuote` (6217). * `stamp_book` needs any signed price that breaches the level, inside the `W_ko` look-back. * To obtain a quote, see [Getting prices](/sdk/prices). ## Two more rules * **A client may settle its own requested close** in the first window, with the window quote. That keeps the first price. If nobody settles in `W` slots, the next window's price applies, and a knockout price in between counts. The count of rolled exits is public: `SettlementReceipt.window` is not 0 for them. * **Read a position through the SDK's accessors**: `phase`, `isUnfilled`, `pendingAdd`, `addTargetSlot`, `addMemo`, `memoIsLive`, `exitTargetSlot`, `exitReason` and `tpFloorSlot`. The same raw bytes of a position mean different things in different states. See [reading positions](/sdk/positions#orders-and-pending-steps). ## What a client must never assume * **That the price on screen at the tap is the entry or the exit.** It is the next price after the delay. * **That a landed `open` is a position.** It is an order until `EntryFilled`. * **That a landed `request_close` is a close.** It is a close at `SettlementPriced`. * **That `PositionOpened` carries the entry.** It has no price field. A position's `entryPrice` on the book is 0 until `EntryFilled`. Take entries from `EntryFilled` and `CollateralAdded`, and returns from `OpenVoided` and `AddReversed`. * **That a price in one of Minute's round events is a price.** See [integrating Minute](/minute/integrating#events-of-an-order). * **That a second transaction is safe after a timeout.** Never sign a second order for the same intent inside one blockhash life. Send the same signed bytes again. * **That adds are on.** `addCollateralFor` refuses to build one while they are off. * **That a void or a reversal is an error.** It is a normal outcome, and the stake comes back (`refundTotal`). * **That two events in one slot are in time order.** Order by `quoteSlot`. Join every venue event on `openerTag`. ## Events | Event | When | What to read | | - | - | - | | `PositionOpened` | the order lands | `seq`, `openerTag`. No price | | `EntryFilled` | a filler writes the entry | `entryPrice`, `entryExpo`, `quoteSlot`, `commitSlot`, `collateral` | | `OpenVoided` | the order is returned | `cause`, `refundTotal`, `feeKept`, `delivered`, `commitSlot` | | `CollateralCommitted` | the add lands | `addedCollateral`, `totalDebit`, `timerAfterS`, `addTarget` | | `CollateralAdded` | a filler prices the add | `entryPrice`, `entryPriceBefore`, `addedCollateral` | | `AddReversed` | the add is returned | `cause`, `refundTotal`, `feeKept`, `timerAfterS`, `delivered` | | `CloseRequested` | the request lands | `exitTarget`, `viaSettle` | | `ExpiryMarked` | the mark lands | `reason`, `exitTarget` | | `KnockoutBeforeAdd` | a price from before a filled add proves a knockout | `quoteSlot`, `oldEntryPrice`, `addedCollateral` | | `SettlementPriced`, `SettlementReceipt` | the close | the receipt's `window`, `exitFeeTotal`, `payoutTrader`, `exitFeeBps`, `entryQuoteSlot`, `exitQuoteSlot` | Each has a decoder: `decodeEntryFilled`, `decodeOpenVoided`, `decodeCollateralCommitted`, `decodeAddReversed`, `decodeCloseRequested`, `decodeExpiryMarked`, `decodeKnockoutBeforeAdd` and `decodeSettlementReceipt`. On a landed transaction, `receiptOf` and `venueEventsNamed(receipt, 'EntryFilled')` read them all. Every event carries `owner`, `market` and `seq`, and the events of a position carry its `openerTag`. ## Refusals a client can get The codes are fixed. `retryClassOf(code)` gives the class of each one, and `RETRY_CLASS_LABEL` the words: see [error handling](/sdk/errors#orders-closes-and-stamps). | Instruction | Error | What the client does | | - | - | - | | `open`, `add_collateral` | `TimerBelowFloor` (6225) | Use a timer of at least the timer floor (26 seconds by default; read `config.timerFloorS`), or none. After an add, the deadline must be at least the timer floor after the add lands. | | `open`, `add_collateral` on feed kind 2, 3 or 4 | `LazerCommitShape` (6350) | Rebuild the transaction in [the commit's shape](#the-commits-transaction-shape-feed-kinds-2-3-and-4). | | `open`, `add_collateral` on feed kind 3 or 4 | `CoverMarketFull` (6267), `CoverGlobalFull` (6268) | The pool cannot cover the order now. Nothing moved. Try again when the pool has room. | | `open`, `add_collateral` on feed kind 4 | `BedrockHalted` (6367), `BedrockStakeCapExceeded` (6371) | The market is halted; the side is at its stake limit (send less, or later). Do not retry in a loop. | | `set_take_profit` | `TakeProfitRaiseRefused` (6346) | The new target is wider than the current one. Keep it or narrow it. | | `open`, `add_collateral` | `ProtocolPaused` (6046), `MarketPaused` (6047), `OracleFrozen` (6190), `SettlesDisabled` (6191) | The venue or the market is stopped. Do not retry in a loop. | | `open`, `add_collateral` | `MarketClosed` (6094), `SessionEndsBeforeTenor` (6095), `InsideEventWindow` (6048) | The market's calendar. | | `add_collateral` | `AddsDisabled` (6212), `EntryNotFilled` (6203), `AddPending` (6211), `ExitPending` (6213) | Adds are off; wait for the entry; wait for the earlier add; a close is on its way. | | `request_close` | `EntryNotFilled` (6203), `AddPending` (6211), `ExitPending` (6213) | Wait; wait; the close is already requested. | | `request_close` | `MinimumHoldNotMet` (6103), `MarketHoldNotMet` (6236) | Wait for the hold: `closableFromSlotOf` gives the slot. | | `request_close` | `OracleFrozen` (6190), `SettlesDisabled` (6191) | The venue is stopped. Do not retry in a loop. | | `request_close` | `ModeBitOff` (6228) | Close requests are switched off. Do not retry in a loop. | | `settle` sent by a client | `ExitNotAnchored` (6214), `ExitPending` (6213) | Request or mark first; the owner's close is already requested, so treat it as success. | | `settle` sent by a client | `ExitQuoteNotYetDue` (6216), `NotWindowQuote` (6217), `ExitReasonMismatch` (6215) | Wait for the target slot; use the quote of the current window; send the recorded reason. | | `settle` sent by a client | `NoFreshPrice` (6007) | The quote is bad or dated ahead of the chain, or the venue is frozen. | | `settle` sent by a client | `OracleFrozen` (6190), `SettlesDisabled` (6191), `WrongMarketForPosition` (6070) | The venue is stopped, so do not retry in a loop; pass the position's own market. | | `stamp_book` sent by a client | `ProofNotAfterEntry` (6218), `ProofTooOld` (6219) | That quote can never prove it; it is too old. | | `stamp_book` sent by a client | `AddPending` (6211), `ExitPending` (6213), `OracleFrozen` (6190), `SettlesDisabled` (6191) | Wait for the end of the add's window; the quote is later than the exit price; the venue is stopped. | | `fill` | `NotAListedFiller` (6205) | A client cannot fill. | When the venue stops taking orders, `open` and `add_collateral` return `ProtocolPaused` (6046) and `config.paused` is true, as for any pause. `set_take_profit` returns it too. Closes, timer ends and knockouts keep working, and an order already placed is filled or returned as usual. See [risk](/risk#when-the-venue-pauses). # Reading positions Source: https://docs.rekt.money/sdk/positions The position handle, the trader account, the two price levels, the two clocks, and what every close would pay right now. ## A slot index is not a position The mistake that costs a builder their *second* trade rather than their first. Positions live in numbered slots inside one trader account, and **slots are reused**. Index 3 today and index 3 tomorrow are different trades. So the SDK never hands you a bare index: ```ts theme={"dark"} import { type PositionRef } from '@rekt-trading/1000x'; // { trader: string; slot: number; seq: bigint } export function describe(ref: PositionRef): string { return `${ref.trader.slice(0, 8)} slot ${ref.slot} seq ${ref.seq}`; } ``` `seq` is what `settle` is called with, and the program searches by it rather than indexing — so a stale handle finds nothing instead of closing a neighbour. Persist `seq`. Treat `slot` as a rendering detail. ## Read a trader's book ```ts theme={"dark"} import { Connection, PublicKey } from '@solana/web3.js'; import { INITIAL_POSITION_SLOTS, decodeTraderAccount, freeSlots, heldPositions, slotCapacity, traderPda, type HeldPosition, } from '@rekt-trading/1000x'; export interface Book { positions: HeldPosition[]; free: number; capacity: number; /** A payout already settled but not yet claimed, and when it becomes sweepable. */ pendingPayout: bigint; pendingSince: bigint | null; } export async function readBook(connection: Connection, owner: PublicKey): Promise { const info = await connection.getAccountInfo(traderPda(owner).address, 'confirmed'); // A trader who has never traded has no account. That is a state, not an error. if (!info) { return { positions: [], free: INITIAL_POSITION_SLOTS, capacity: INITIAL_POSITION_SLOTS, pendingPayout: 0n, pendingSince: null, }; } const account = decodeTraderAccount(new Uint8Array(info.data)); // Capacity comes from the account's ALLOCATION, not from `slots.length` — the vector holds only // as many entries as have ever been used, so a four-slot account reports 1 after its first close. const capacity = slotCapacity(info.data.length); return { positions: heldPositions(owner.toBase58(), account), free: freeSlots(account, capacity), capacity, pendingPayout: account.pendingPayout, pendingSince: account.pendingPayout > 0n ? account.pendingSince : null, }; } ``` `heldPositions` returns live positions only, each already bound to its handle: `{ ref, position }`. Free slots are not returned — an empty slot is not a thing a user has. > [!NOTE] > > `PositionSlotsFull` is neither a validation error nor an outage. It means *close something > first*. A slot frees when a settle for its position lands. A new book takes 12 slots by default and > can hold up to 21, or up to the venue's book capacity (at most 63) with the `GovTable` passed; `resizeTraderAccount` > grows it, with the owner's and the rent payer's signatures. The rent payer pays for the extra slots and gets it back at close. ## Check for a free slot before you send A full book refuses the open with `PositionSlotsFull` (6056), and the transaction still pays its fee. Read the book just before you build the open: ```ts theme={"dark"} import { fetchFreePositionSlots } from '@rekt-trading/1000x'; const slots = await fetchFreePositionSlots(connection, owner); // one getAccountInfo, at `confirmed` if (slots.free === 0) { // Wait for a settle to land, or grow the book with `resizeTraderAccount`. } ``` `freePositionSlots(bytes)` does the same from bytes you have already read. It returns `{ exists, capacity, live, free }`. `capacity` is the book's own size, from its byte length: older books and resized books differ from 12. With no book yet, it is the size a new book is created with. **A slot is in use until the settle of its position lands.** A knockout, a timer that ran out or a result you have already shown does not free it; the keeper's settle does, some seconds later. Count the free slots from the chain, not from your own record of which positions have ended. ## What a position remembers The terms are **frozen at open, against governance**. A position carries its own barrier, rung, exit fee bound, cap, tenor, funding rate and funding grace, and the fee terms entry it froze (`feeTermsSlot(position.flags)`). Settlement reads those rather than live config. A governance change does not reach a position that already exists. **The freeze is against governance, not against the owner.** The owner may add collateral to a live position. An add moves `collateral`, `entryPrice`, `openedSlot` and `reserved`, and writes `userTimerS` if the add sets one. Nothing writes a level, because the barrier and the take-profit are *distances* from the entry: writing `entryPrice` is the whole of "recompute the barrier from the new average entry". So a cached `levels()` result goes stale on an add even though no level was written. See [adding to a position](/how-it-works#adding-to-a-position). | Field | Meaning | | - | - | | `seq` | The handle. | | `market` | The market address this position belongs to. Check it before you price anything. | | `collateral` | The stake. | | `tier` | The leverage it opened at. | | `direction` | `0` long, `1` short — the raw on-chain discriminant. | | `entryPrice`, `entryExpo` | Where it opened, and at what exponent. **0 while the position is an order.** | | `barrierMicroBp`, `takeProfitMicroBp` | The two levels, as distances from entry. | | `exitFeeBps`, `payoutCapMultiple` | Frozen at open, not read from live config. `exitFeeBps` is the exit fee **bound**: a position with a fee-terms slot pays the rate its terms entry gives, never above it. | | `borrowRateBpsPerHour` | The funding rate this position pays, frozen at open. The funding rate is 0, so nothing accrues. Read this field, never `config.params.borrowRateBpsPerHour`, which is what a *new* position would freeze. | | `borrowGraceS` | The free window before funding accrues, frozen at open. A stored `0n` resolves to the live `config.params.borrowGraceS`. | | `openedAt`, `openedSlot`, `tMaxSeconds`, `userTimerS` | The two clocks and their origins. | | `reserved` | The reserve the cover rule counts for this position: its maximum payout and closing fee. Grows on an add. | > [!WARNING] > > **`openedAt` and `openedSlot` are two different clocks and an add moves only one of them.** > > `openedSlot` is the slot of the price that last priced the position: the order's slot until a filler > writes the entry, then the slot of the entry price, and after a filled add the slot of the add's > price. The minimum hold counts from it, so a double-down restarts the hold before a close the owner > asks for. > > `openedAt` is not re-stamped by an add. > [!WARNING] > > **`position.market` is an address.** A client holding two markets must check it before pricing — > an interface that prices a SOL position against another market's median quotes the wrong payout > *and* submits the wrong market to `settle`. The program catches only the second of those. ## Orders and pending steps A slot can hold an **order** as well as a position, and a position can be waiting for a step: an add that waits for its price, a short hold after a filled add, or an exit target from a close request or an expiry mark. Read the state with `phase(position, nowSlot)`: | Phase | What it is | | - | - | | `PendingOpen` | An order. `entryPrice` is 0. No close, add or level exists yet. | | `Live` | Filled, nothing pending. | | `AddPending` | An add waits for its price. | | `AddMemo` | An add was filled, and its short hold (`M_add` slots) is still running. | | `ExitRequested` | The owner requested a close. Anyone may settle it from the exit target. | | `ExitMarked` | An expiry was marked. Anyone may settle it from the exit target. | | `StampedKnockedOut`, `StampedTookProfit` | A level is stamped. The settle pays it. | | `StampedAddPending` | Stamped knocked out, with an add still to return. | **Read the pending steps through the accessors, never through the raw fields.** The same last words of a position hold a pending add, the memo of a filled add, or nothing, depending on a flag, and several store a slot as an offset from `openedSlot`. `isUnfilled`, `pendingAdd`, `addTargetSlot`, `addMemo`, `memoIsLive`, `exitTargetSlot`, `exitReason` and `tpFloorSlot` decode them as the program does. `closableFromSlotOf(position, config, market)` gives the first slot at which a close request can land, or `null` while there is none. Do not draw levels for an order: `levels` needs an entry. See [orders and closes](/sdk/orders). ## The two price levels `barrierMicroBp` and `takeProfitMicroBp` are distances. `levels` turns them into the prices a chart can draw. Each price is the program's own threshold: the first price at which the barrier counts as touched, or the take-profit as reached — never one base unit short of it. `takeProfitPrice` is `null` when the position has no take-profit, and when the level would fall at a price of zero, which no oracle reports. ```ts theme={"dark"} import { levels, type PositionView } from '@rekt-trading/1000x'; export function lines(position: PositionView): { barrier: bigint; takeProfit: bigint | null } { const l = levels(position); return { barrier: l.barrierPrice, // null when the position has no rung set, or the level would be a zero price. takeProfit: l.takeProfitPrice, }; } ``` ## The two clocks ```ts theme={"dark"} import { deadlines, isIndefiniteTenor, type PositionView } from '@rekt-trading/1000x'; export function countdown(position: PositionView, nowUnix: bigint) { const d = deadlines(position); // A position that froze the indefinite tenor has no protocol clock: show "no limit", never a date. const noTenor = isIndefiniteTenor(position.tMaxSeconds); return { // The protocol's tenor, from the position's own frozen value. null means no limit. tenorIn: noTenor ? null : d.tenorExpiresAt - nowUnix, // The trader's own timer, if they set one. userIn: d.userExpiresAt === null ? null : d.userExpiresAt - nowUnix, // The earlier of the two: when a stranger may first close this position. Under the indefinite // tenor it is your own timer, or null when you set none. closableBy: noTenor ? d.userExpiresAt : d.firstExpiryAt, }; } ``` ## What every close would pay, right now `settlePreview` prices the **six priced close reasons** at one price and one instant, using the same settlement the chain runs, and says which are legal now and why the others are not. It does not model `lastResort`, the no-price close; see [settling a position](/sdk/settling#the-close-reasons). **What a close pays.** The program takes these steps in this order, with the terms the position froze at open: 1. On a gain, the stake plus the part of the gain you keep. On a loss, the stake less the loss. 2. On a loss, a **loss tax** of 42.85 % of the realised loss comes out of that. It is taken before the exit fee, so a close at a loss returns about the stake less 1.43 times the loss, before the fee. 3. The exit fee, on the exit value that is left after the tax. 4. Funding, from the position's frozen rate. The rate is 0, so a quote has no funding line. What remains is paid, up to the payout cap. A knockout pays 0 and takes no fee. [Fees and limits](/limits) has the rates. Pass the market's fee-terms account, decoded, for a position with a fee-terms slot (`feeTermsSlot(position.flags) != 0`). The close is then priced with that slot's entry, as the chain prices it. Without the account such a close reads `FeeTermsTableRequired`. `client.settlePreview` takes the same `{ feeTermsTable }` as its last argument. ```ts theme={"dark"} import { settlePreview, type CloseReasonName, type ConfigView, type FeeTermsTableView, type PositionView, type SettlePreview, } from '@rekt-trading/1000x'; export function preview( position: PositionView, config: ConfigView, exitPrice: bigint, nowUnix: bigint, signer: string, owner: string, feeTermsTable: FeeTermsTableView | null, ): SettlePreview { const out = settlePreview(position, config, exitPrice, nowUnix, signer, owner, { feeTermsTable }); // How far the move has travelled toward the barrier, 0 to 1. Above 1 means knocked out. console.log(`barrier fraction ${out.barrierFraction.toFixed(3)}`); console.log(out.knockedOut ? 'knocked out' : out.takeProfitReached ? 'rung reached' : 'live'); for (const r of out.reasons) { const name: CloseReasonName = r.reason; console.log( r.legal // `payouts.liquidator` reads 0n on every settlement: nobody is paid to submit a close. ? `${name}: trader ${r.payouts?.trader}, protocol ${r.payouts?.protocol}${r.capped ? ' (CAPPED)' : ''}` : `${name}: not legal: ${r.why}`, ); } // `out.suggested` is the reason a keeper would submit, or null when none is legal yet. return out; } ``` `signer` and `owner` are separate arguments because **`voluntary` is the one reason that needs the owner's authority behind it**: their own signature, or a session key they authorised. Every other reason is proved by the price or by the clock and is therefore permissionless. Conflating the two is how an interface offers a button that cannot work. > [!WARNING] > > **`settlePreview` marks `voluntary` legal only when `signer === owner`.** The program also admits > an unexpired session key whose owner is the position's owner, so a Close button gated on this > report alone stays hidden for a close a session key can sign. `NotPositionOwner` (6072) is raised > only when no session key is supplied. ## Where settlements pay Every settlement of a position pays the book's recorded `payoutDestination`. It is set at `initTraderAccount` and the owner may move it with `setPayoutDestination`, signed by the owner alone: no session key and no other authority can. The new account must be a USDC account the owner owns, on the vault's mint, and not frozen. Moving it does not touch a payout already held on the book, and does not restart that payout's expiry clock. ```ts theme={"dark"} import { ix, toHex, traderPda, vaultPda, type BuiltInstruction } from '@rekt-trading/1000x'; import { PublicKey } from '@solana/web3.js'; export function buildSetDestination(args: { owner: PublicKey; vaultToken: PublicKey; newDestination: PublicKey; }): BuiltInstruction { return ix.setPayoutDestination({ owner: toHex(args.owner), positions: toHex(traderPda(args.owner).address), vault: toHex(vaultPda().address), vault_token: toHex(args.vaultToken), payout_destination: toHex(args.newDestination), }); } ``` A settle that names any other account as `owner_token` does not pay it: the payout is held on the book instead. Read the destination off the book (`decodeTraderAccount(bytes).payoutDestination`) whenever you build a settle. ## A payout that has not been collected When a settlement cannot deliver, because the destination was closed, frozen or not the recorded one, the payout is held on the trader's book as `pendingPayout`. Show it: it is money the user already has and may not know about. ```ts theme={"dark"} import { ix, toHex, traderPda, vaultPda, type BuiltInstruction } from '@rekt-trading/1000x'; import { PublicKey } from '@solana/web3.js'; export function buildClaim(args: { payer: PublicKey; owner: PublicKey; ownerToken: PublicKey; vaultToken: PublicKey; }): BuiltInstruction { return ix.claimPayout({ payer: toHex(args.payer), owner_token: toHex(args.ownerToken), positions: toHex(traderPda(args.owner).address), vault: toHex(vaultPda().address), vault_token: toHex(args.vaultToken), }); } ``` * **To the recorded destination, anyone may claim.** No owner signature is needed, and the money can go nowhere the settlement would not have sent it. * **To any other account, the owner must be the `payer` and sign.** Otherwise the claim is refused (`ClaimDestinationRequiresOwner`, 6155). The destination must still be a USDC account the owner owns. A payout nobody claims within `config.params.unclaimedPayoutExpiryS` of when it was held (`pendingSince`) may be swept to the liquidity pool by anyone, with `sweepUnclaimedPayout`. Next: [settling a position](/sdk/settling). # Getting prices Source: https://docs.rekt.money/sdk/prices Where a bot gets a signed quote, what the request looks like, how the program verifies it, and how public use is limited. Quotes come from **`https://prices.rekt.trading`**. There is no other address. Use TLS everywhere. The stream is `wss://prices.rekt.trading/v1/stream`. Only the instructions that read a price need a quote: `settle`, `stamp_book`, `set_take_profit` and `prove_price`. An open, an add and a close request carry none. The price service quotes the markets of feed kind 2. A market of feed kind 3 (`isKind3Market(market)`) is priced by a signed tick that the venue's fillers and keepers attach, and a quote from this service does not price it: a client of that market opens, adds and requests closes, and needs no price at all. A market of feed kind 4 reads an on-chain oracle inside the venue's instruction, and a quote from this service does not price it either. Read `market.feedKind[0]` on every request: a market's kind can change. A quote from the service is 80 bytes, signed by several keys. The service signs payload version 1 (the default) or version 2: ask for version 2 with `payload_version: 2`. **The Knockout program verifies the signatures on chain**, and refuses a quote that fails any check on [Quotes and freshness](/sdk/quotes). Nothing the service returns outside the signed bytes is authoritative. | Endpoint | Purpose | | - | - | | `GET /v1/feeds` | The feeds the price service signs, its signer keys, and each feed's `feed_id`. A feed is not a market: the list can carry a feed whose market is not open to trade or is not of feed kind 2. The open markets are on [markets](/markets) | | `POST /v1/quote` | A signed quote for one feed | | `GET /v1/stream` | WebSocket: signed quotes as they are produced | | `GET /v1/readiness` | Whether each feed can be quoted right now, and its market session | | `GET /v1/health` | Whether the service process is alive | ## The loop 1. **Once, at start-up.** `GET /v1/feeds`. Take the feeds of the markets you trade. A market's feed is `market.feeds[0]`; it equals the `feed_id` listed for that symbol. Pin it. 2. **When you are about to act.** `POST /v1/quote`, or hold a stream open and keep the latest frame. 3. **Judge it.** `benchmarkQuoteView` turns a quote into the view the [gates](/sdk/gates) judge: `priceGates` applies the program's own admission rule before you spend a fee. 4. **Send it.** `submitBenchmarkQuoted` places the quote's ed25519 instruction immediately before yours in the same transaction and sends it. See [Settling a position](/sdk/settling#send-it-with-its-quote). 5. **On a refusal, read the status.** `409` and `429` are retryable after `retry_after_ms`. Every other `4xx`, such as `400`, is not: fix the request. ```sh theme={"dark"} curl -s https://prices.rekt.trading/v1/feeds curl -s https://prices.rekt.trading/v1/quote \ -H 'content-type: application/json' \ -d '{"feed":"SOL/USD","payload_version":2,"idempotency_key":"'"$(openssl rand -hex 16)"'"}' ``` The response carries `payload` (the signed bytes, hex), `signatures`, `ed25519_instruction_data` (the complete instruction, ready to place before yours) and `decoded`, a mirror for reading. Decide on the bytes, not on `decoded`. ## Rules that matter * **A quote ages out.** The program judges its age at execution, against `market.maxOracleAgeSlots`. Fetch a new quote for every attempt, with a new `idempotency_key`. Reuse a key only for an immediate retry after a transport failure. * **A window quote is the first quote at or after a slot.** Ask for it with `min_slot` and `payload_version: 2`. Every caller who asks for the same slot gets the same bytes. * **A failure is never a price.** A refusal has a status, a reason and a retry hint. * **A market with trading hours says so inside the signature.** A closed session signs no price. See [Markets](/markets). * **Call the service from a server, not from a browser.** It sends no CORS headers, so a browser cannot call it. Keep a token out of URLs. If you have one, send it as `Authorization: Bearer `. ## Limits Public use needs no sign-up and is rate limited per client address, so clients behind one address share a limit. A limited request gets `429` with `retry_after_ms` and a `Retry-After` header. A limit says nothing about whether a feed is healthy. * Use the stream rather than polling for the latest price. * Fetch `GET /v1/feeds` at start-up, not per request. * Back off with jitter on `429` and `503`, and honour `retry_after_ms`. * Keep one stream connection per process. **For higher limits, write to [support@asymmetra.xyz](mailto:support@asymmetra.xyz).** These pages describe the interface. They do not describe how prices are produced. # Quickstart Source: https://docs.rekt.money/sdk/quickstart A bot in one file that quotes, opens and closes a position through the SDK. Copy it, set two variables and run it. This page gives you a bot to copy. It reads the chain, quotes a trade, opens it, waits for the fill, closes it and prints what it was paid. It runs as a dry run until you tell it to send. ## Try it with no money [Wheelman](/tools/wheelman) is a bot and command line built on this SDK. Its paper mode reads the live markets, simulates the fill and sends nothing. A paper trade needs an RPC endpoint and no SOL or USDC. Wheelman needs Node 22.18 or later, and it runs from a clone of its repository: ```sh theme={"dark"} git clone https://github.com/Asymmetra/rekt-wheelman wheelman && cd wheelman npm install && npm link wheelman setup # a wallet, your RPC endpoint, the risk limits; writes .env wheelman open BTC long 1 --paper # a paper position: simulated, nothing sent wheelman positions --paper # the paper account ``` A paper result does not say what live trading pays. The dry run of the bot on this page is different. It builds the real transaction and simulates it on mainnet, so the wallet must hold SOL and USDC before the dry run works. A simulation refuses a fee payer with no SOL, and the bot stops when the wallet has no USDC account. ## Set up You need Node 20.19 or later (or Node 22.12 or later), a Solana keypair file, a little SOL for fees, and USDC in the wallet. **1. Make a project.** The SDK is ESM-only, so the project needs `"type": "module"`. ```sh theme={"dark"} mkdir rekt-bot && cd rekt-bot npm init -y npm pkg set type=module npm install @rekt-trading/1000x@^0.8.0 @solana/web3.js npm install --save-dev tsx typescript ``` **2. Make a keypair.** Save this as `keypair.ts` and run `npx tsx keypair.ts`. It writes the secret key to `keypair.json` and prints only the public address. Keep that file out of version control and out of every prompt and log. ```ts keypair.ts theme={"dark"} import { writeFileSync } from 'node:fs'; import { Keypair } from '@solana/web3.js'; const key = Keypair.generate(); writeFileSync('keypair.json', JSON.stringify([...key.secretKey]), { mode: 0o600 }); console.log(key.publicKey.toBase58()); // the address to fund ``` **3. Fund the address.** Send about 0.01 SOL, which covers fees and the rent of the book a first trade creates, and USDC on Solana for the stake. Buy USDC at an exchange and withdraw it to that address on the Solana network, or swap SOL for USDC in a wallet and send it over. The first USDC deposit creates the token account the bot uses. The smallest stake is \$0.20. See [Fees and limits](/limits). ## The bot Save this as `bot.ts`. ```ts bot.ts theme={"dark"} // bot.ts: quote, open and close one position on Rekt Knockout. // // npx tsx bot.ts dry run: reads the chain, quotes, simulates, sends nothing // SEND=1 npx tsx bot.ts sends: opens, waits for the fill, closes, prints the payout // // Set SOLANA_RPC_URL (an RPC endpoint) and KEYPAIR_PATH (a Solana keypair file). With SEND=1 this // spends real USDC, so start with a small STAKE_USDC. import { readFileSync } from 'node:fs'; import { ComputeBudgetProgram, Connection, Keypair, PublicKey, TransactionMessage, VersionedTransaction, } from '@solana/web3.js'; import { assetId, chainNowSeconds, closableFromSlotOf, computeUnitLimit, configPda, connectionReader, decodeConfig, decodeMarket, decodeTraderAccount, decodeVault, errorForCode, findBySeq, ix, landedOpenedSeq, marketPda, openPreview, ourInstruction, parseUsdc, priceAccountsFor, programErrorCode, readSettlementForSeq, requestCloseFor, sizeForTotal, toHex, traderPda, vaultPda, type BuiltInstruction, } from '@rekt-trading/1000x'; const SYMBOL = process.env['MARKET'] ?? 'BTC'; const BUDGET = parseUsdc(process.env['STAKE_USDC'] ?? '1.00'); // the most that leaves your wallet const RUNG_BPS = 20_000; // a 2.00x target. Basis points of stake: 20_000 is the lowest target. const SEND = process.env['SEND'] === '1'; const url = process.env['SOLANA_RPC_URL']; const keypairPath = process.env['KEYPAIR_PATH']; if (!url || !keypairPath) throw new Error('set SOLANA_RPC_URL and KEYPAIR_PATH'); const connection = new Connection(url, 'confirmed'); const wallet = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(keypairPath, 'utf8')))); const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const usd = (n: bigint) => `$${n / 1_000_000n}.${(n % 1_000_000n).toString().padStart(6, '0').slice(0, 2)}`; /** A price from the chain is an integer at an exponent: 6_543_210_000_000n at -8 is 65432.10000000. */ const price = (raw: bigint, expo: number) => { if (expo >= 0) return (raw * 10n ** BigInt(expo)).toString(); const digits = raw.toString().padStart(1 - expo, '0'); return `${digits.slice(0, expo)}.${digits.slice(expo)}`; }; async function read(address: PublicKey): Promise { const info = await connection.getAccountInfo(address, 'confirmed'); return info === null ? null : new Uint8Array(info.data); } async function must(address: PublicKey, what: string): Promise { const bytes = await read(address); if (bytes === null) throw new Error(`${what} does not exist at ${address.toBase58()}`); return bytes; } /** Ask `probe` until it answers, for at most `ms`. */ async function until(what: string, ms: number, probe: () => Promise): Promise { const deadline = Date.now() + ms; for (;;) { const answer = await probe(); if (answer !== null) return answer; if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`); await sleep(500); } } /** Build, simulate and (with SEND=1) send one transaction. A refusal is reported by name. */ async function run(label: string, built: BuiltInstruction[], units: number): Promise { const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed'); const message = new TransactionMessage({ payerKey: wallet.publicKey, recentBlockhash: blockhash, instructions: [ ComputeBudgetProgram.setComputeUnitLimit({ units }), ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1_000 }), ...built.map(ourInstruction), ], }).compileToV0Message(); const tx = new VersionedTransaction(message); tx.sign([wallet]); const sim = await connection.simulateTransaction(tx, { commitment: 'confirmed' }); if (sim.value.err !== null) { const refusal = errorForCode(programErrorCode(sim.value.err) ?? -1); // `retryable` says what to do next: `never` means fix the request, `after-state-changes` means wait. throw new Error( `${label} refused: ${refusal ? `${refusal.name} (${refusal.retryable}) ${refusal.fix}` : JSON.stringify(sim.value.err)}`, ); } if (!SEND) { console.log(`${label}: simulated, ${sim.value.unitsConsumed} compute units. Dry run: nothing sent.`); return null; } const signature = await connection.sendTransaction(tx); const done = await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed'); if (done.value.err !== null) throw new Error(`${label} reverted: ${signature}`); console.log(`${label}: landed ${signature}`); return signature; } async function main() { // 1. Read the protocol. Never cache it: every parameter is governed. const market = decodeMarket(await must(marketPda(assetId(SYMBOL)).address, `the ${SYMBOL} market`)); const config = decodeConfig(await must(configPda().address, 'the config')); const vault = decodeVault(await must(vaultPda().address, 'the vault')); const nowUnix = BigInt(await chainNowSeconds(connection)); const vaultToken = new PublicKey(Buffer.from(vault.tokenAccount, 'hex')); // 2. Quote. `sizeForTotal` turns a budget into a stake. `openPreview` says what it costs and pays. const size = sizeForTotal(BUDGET, config.params); if (size.refusal) throw new Error(`${size.refusal.error}: ${size.refusal.detail}`); const quote = openPreview(config, market, size.collateral, RUNG_BPS, nowUnix); if (quote.barrierPayout === null) throw new Error('the engine refuses these terms'); console.log( `quote ${SYMBOL}: stake ${usd(size.collateral)}, you pay ${usd(quote.totalDebit)}, ` + `gross at the target ${usd(quote.maxPayout)} (before the exit fee and the share of the gain the terms withhold), ` + `at the barrier ${usd(quote.barrierPayout)}`, ); // 3. Open. Your USDC account is your wallet's associated token account on the vault's mint. const mint = new PublicKey((await must(vaultToken, 'the vault token account')).subarray(0, 32)); const [usdc] = PublicKey.findProgramAddressSync( [wallet.publicKey.toBytes(), new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA').toBytes(), mint.toBytes()], new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'), ); await must(usdc, 'your USDC account'); const book = traderPda(wallet.publicKey).address; // one account holds all your positions const me = toHex(wallet.publicKey); // the program takes addresses as hex const accounts = { config: toHex(configPda().address), market: toHex(marketPda(assetId(SYMBOL)).address), vault: toHex(vaultPda().address), vault_token: toHex(vaultToken), positions: toHex(book), }; const open = ix.open( { authority: me, trader_token: toHex(usdc), config: accounts.config, market: accounts.market, vault: accounts.vault, vault_token: accounts.vault_token, protocol_token: config.treasury, positions: accounts.positions, delegate: null, }, { budget: BUDGET, direction: 0, // 0 long, 1 short rung_bps: RUNG_BPS, user_timer_s: 0, // no timer of your own min_collateral_out: size.collateral, // the smallest stake you accept for this budget referrer: null, tier: 0, // 0 is the market's own leverage opener_tag: 0n, }, // The market's own list: the governance table on a feed-kind-3 market, then the fee-terms account // when the market has one. No quote on either kind. priceAccountsFor(market, config, 'open'), ); // A first trade also creates the book, in the same transaction. const first = (await read(book)) === null; const createBook = first ? [ ix.initTraderAccount( { trader: me, payer: me, positions: accounts.positions, vault: accounts.vault, vault_token: accounts.vault_token, payout_destination: toHex(usdc), // every payout of this book goes here }, 4, // room for four positions at once; 1 to 21 ), ] : []; const units = computeUnitLimit('open') + (first ? computeUnitLimit('init_trader_account') : 0); const signature = await run('open', [...createBook, open], units); if (signature === null) return; // a dry run stops here // 4. The open is an order. The venue's next price fills it, or returns it with your whole stake. const landed = await connection.getTransaction(signature, { commitment: 'confirmed', maxSupportedTransactionVersion: 0 }); const opened = landedOpenedSeq({ logs: landed?.meta?.logMessages ?? null, returnData: null, owner: me, market: accounts.market, }); if (opened.seq === null) throw new Error(opened.why); const seq = opened.seq; // the handle of your position; never use the slot index const find = async () => { const bytes = await read(book); return bytes === null ? null : findBySeq(decodeTraderAccount(bytes), seq); }; const filled = await until('the fill', 60_000, async () => { const position = await find(); if (position === null) return 'returned' as const; // the order was returned return position.entryPrice !== 0n ? position : null; }); if (filled === 'returned') return console.log('the order was returned: your whole stake came back'); console.log(`filled at ${price(filled.entryPrice, filled.entryExpo)}`); // entryPrice alone is not a price // 5. Close. A close is a request, and the venue's keepers complete it. You cannot ask in the first // slots after the entry; the SDK says which slot is the first. const from = closableFromSlotOf(filled, config, market); while (from !== null && BigInt(await connection.getSlot('confirmed')) < from) await sleep(400); await run( 'close', [ // `requestCloseFor` adds the governance table on a feed-kind-3 market, which refuses a request without it. requestCloseFor( market, { authority: me, config: accounts.config, market: accounts.market, positions: accounts.positions, delegate: null }, seq, ), ], computeUnitLimit('request_close'), ); await until('the settlement', 120_000, async () => ((await find()) === null ? true : null)); // 6. Read what the close paid. Part of a win can be paid later: see "how a win is paid". const [trade] = await readSettlementForSeq(connectionReader(connection), wallet.publicKey, [seq], config); console.log(trade ? `closed (${trade.reason}): paid ${usd(trade.payouts.trader)} now` : 'closed: read the settlement from your history'); } main().catch((error) => { console.error(error instanceof Error ? error.message : error); process.exit(1); }); ``` ## Run it ```sh theme={"dark"} export SOLANA_RPC_URL="" export KEYPAIR_PATH="$PWD/keypair.json" npx tsx bot.ts # a dry run: quotes and simulates, sends nothing SEND=1 npx tsx bot.ts # sends: opens, waits for the fill, closes ``` Keep the RPC endpoint in an environment variable and out of your source and your logs. Endpoints from a provider carry a key in the URL. ## What each step does 1. **Read the protocol.** The config, the vault and the market are decoded from the chain. Nothing here is cached: every parameter is governed and can move. 2. **Quote.** `sizeForTotal` turns the budget you hand the venue into a stake. `openPreview` says what it costs, the gross payout at the target (before the exit fee and the share of the gain the terms withhold) and what you receive at the barrier, which is nothing. A close between the entry and the barrier pays what is left after the loss, less a loss tax on that loss and then the exit fee, so a loss costs more than the move and the exit fee. See [what a close pays](/sdk/positions#what-every-close-would-pay-right-now). Show the barrier line next to the button in anything a person uses. 3. **Open.** The open is an order. The stake is taken when it lands, and the venue's next price after a short delay fills it. A first trade creates your book in the same transaction. `min_collateral_out` is your floor on the stake, so a fee change in between reverts the open and never shrinks it. 4. **Wait for the fill.** The order is filled, or it is returned and your whole stake comes back. A returned order is a normal outcome. The bot reads your book until it knows which. The handle of a position is its `seq`. A slot index is not a handle, because slots are reused. 5. **Close.** A close is a request that carries no price. You cannot ask in the first slots after the entry, and `closableFromSlotOf` says which slot is the first. `requestCloseFor` builds the request with the accounts the market's feed kind needs. The venue's keepers complete the close. Anyone may. 6. **Read the payout.** Part of a win can be paid later, in order. The bot prints what was paid now. See [how a win is paid](/liquidity#how-a-win-is-paid). ## When something is refused The bot simulates before it sends, so a refusal costs nothing. It prints the name of the refusal and its retry class. Branch on the class and not on the name or the text: | Class | Do | | - | - | | `never` | Fix the request. A retry is a loop. | | `after-state-changes` | Wait for the world to move, then ask again. | | `after-governance` | Stop. Only a change by the venue's authority clears it. | | `immediately` | Retry on the next slot. | [Error handling](/sdk/errors) lists every refusal a client sees. [Reading gates](/sdk/gates) predicts them before you send. ## Next > [card] [Orders and closes](/sdk/orders) > > The contract a bot builds against: fills, returns, close requests and the events for each. > [card] [Read the protocol](/sdk/reading) > > The read path on its own, with the oracle shape and the gate report. > [card] [Fees and limits](/limits) > > What a trade costs and the limits it meets. Dated, and they can change. > [card] [Build with an AI agent](/sdk/ai) > > The docs as an MCP server, `llms.txt`, and a skill file an agent can load. # Quotes and freshness Source: https://docs.rekt.money/sdk/quotes What a quote is, which instructions carry one, how a transaction carries it, what the program checks, and what to do when a priced instruction is refused with 6007. Every instruction that prices a position carries its own price. This page is the single reference for that price: its shape, the transaction it rides in, the checks the program applies, and the refusal you will meet most often. > [!NOTE] > > **An `open`, an `add_collateral`, a `request_close` and a `mark_expiry` carry no quote.** The price > of an order is written later by a filler, and the price of a requested or marked exit is the > window quote of the settle. The instructions that carry a quote are `settle`, `stamp_book`, > `set_take_profit`, `prove_price` (`provePrice`), and the filler's `fill` and proof forms. See > [orders and closes](/sdk/orders). ## What a quote is A **quote** is a price signed by the venue's quote service, carried **inside the transaction that uses it**. There is no price account to read. A market of feed kind 2 reads its price this way. A market of feed kind 3 (`isKind3Market(market)`) reads a signed tick that the venue's fillers and keepers attach; a client does not fetch it, and an open, an add and a close request on it carry none. A market of feed kind 4 reads its price from an on-chain oracle program inside the venue's own instruction: there is no quote and nothing to fetch, and the venue's keepers fill, settle and stamp it (see [on-chain oracle markets](/sdk/orders#on-chain-oracle-markets-feed-kind-4)). Read `market.feedKind[0]` for a market's kind on every request: a market's kind can change. `settlementIdentity(market)` gives its identity. The rest of this page is the kind-2 quote. > [!NOTE] > > This page describes what the program verifies and the transaction a quote rides in. **To obtain a > quote, see [Getting prices](/sdk/prices).** ```ts theme={"dark"} import { settlementIdentity, type MarketView } from '@rekt-trading/1000x'; export function isSignedQuoteMarket(market: MarketView): boolean { const s = settlementIdentity(market); // `vendor` is 'benchmark' on a market priced by a signed quote, and `pull` is true: // the price is posted in the caller's own transaction, never read from an account. return s.vendor === 'benchmark' && s.pull; } ``` The quote names the market's feed (`market.feeds[0]`), a price in US-dollar units and the slot it was published in. It arrives with the ed25519 signatures of the service's signing keys over those bytes. > [!WARNING] > > **A price stream is not a precondition for a trade.** A chart feed going quiet says nothing about > whether a trade can land. An open needs no quote at all: a filler writes the entry later. For an > instruction that does carry a quote, the precondition is whether you can obtain a signed quote at > send time and land it before it ages out. That is a request you make, not a state you observe. > [!NOTE] > > **The price you draw on a chart and the price the program verifies are different facts**, and may > come from different sources. Ask `settlementIdentity(market)` which one a market settles on rather > than inferring it from the chart. ## The transaction shape ```text theme={"dark"} 0 ed25519 precompile the signed quote and its signatures 1 settle | stamp_book | ... yours: reads the instruction immediately before it 2 ComputeBudget setComputeUnitLimit 3 ComputeBudget setComputeUnitPrice ``` * **The ed25519 instruction must be immediately before yours.** The program reads the instruction at relative index −1 and refuses anything that is not the ed25519 program. The indices are exported as `BENCHMARK_QUOTED_LAYOUT` (`{ ed25519: 0, instruction: 1 }`). * **The signature records point at their own instruction.** Every offset in the precompile names the precompile itself, so its absolute position does not matter; only its adjacency to yours does. An instruction you add goes **in front of** index 0 or **after** the compute-budget pair, never between the quote and your instruction. * **Your instruction carries the Instructions sysvar as its remaining account.** That is how the program reaches the precompile. `pricingRemainingAccounts(market)` returns exactly that list for a market priced by a signed quote. Do not pass `market.feeds` as accounts: `feeds[0]` is a feed id, not an account. * **`composeBenchmarkTransaction` builds this order and `submitBenchmarkQuoted` sends it.** The sender evaluates the protocol gates you hand it, composes, signs, measures the signed bytes, checks the distinct-signer count against `market.minSignatures`, simulates, and only then sends. `dryRun: true` stops before the send. ## What the program checks The program re-proves the quote at execution. A quote that fails any check counts as no price at all. | Check | Result | | - | - | | The ed25519 instruction is immediately before yours and every record points at itself | no price | | The payload's magic, version byte and length agree | no price | | At least `market.minSignatures` **distinct** signers that the program recognises | not admitted | | The quote is for this market's feed, in US-dollar units | no price | | At least `market.minSources` sources aggregated | no price | | `Clock.slot − publish slot` is at most `market.maxOracleAgeSlots`, and the publish slot is not in the future | not admitted | "Not admitted" and "no price" both end the same way: **`NoFreshPrice` (6007)**. **The age row depends on the instruction.** A settle of a requested or marked exit needs the window quote, which can be any age inside its window. A knockout or take-profit proof must be newer than the entry and inside its look-back. `market.maxOracleAgeSlots` bounds the quote of `set_take_profit`. A quote dated ahead of the chain is refused everywhere. The timing settings are on [orders and closes](/sdk/orders#the-timing-settings). `benchmarkSourceFloor(market, 'settle')` returns the source floor. None of these are constants: read them from the market. ## The one rule that explains every refusal > [!WARNING] > > **The freshness clock is read on chain, at execution, never at the moment you obtained the > quote.** > > The program compares `Clock.slot` against the slot the quote was published in and refuses when the > difference exceeds `market.maxOracleAgeSlots`, or when that age, counted at 215 ms a slot, exceeds > `market.maxOracleAgeMs`. Both fields are governed: read them. The 215 ms is a constant of the > program (`SLOT_MS`); `config.params.slotMs` does not change this check. A mainnet slot takes about > 213 ms today: measure it (`getRecentPerformanceSamples`) when you size a timeout. Everything between obtaining the quote and the transaction landing is charged to that budget: composing, signing, the network carrying the packet to a leader, and the block itself. ```ts theme={"dark"} import { freshnessWindowMs, type ConfigView, type MarketView } from '@rekt-trading/1000x'; // Two governed values, multiplied in one place. Use the result to size timeouts and to explain a // refusal, never to price anything. export function freshnessBudget( market: MarketView, config: ConfigView, ): { slots: number; approxMs: number } { return { slots: market.maxOracleAgeSlots, approxMs: freshnessWindowMs(config.params, market) }; } ``` ## `6007` — `NoFreshPrice` This is the code you will actually meet. It is `retryable: 'immediately'`, and it means one thing: **at the instant the program ran, no quote cleared admission.** The quote was too old, carried too few distinct signers, or, on a settle, failed any of the checks above. ### What it is not * **Not a failed trade.** Nothing moved. No collateral left the wallet, no position opened, no position closed. The only cost is the network fee for the attempt. * **Not a fault in your code.** A quote has a fixed number of slots to survive between being signed and being read. Losing that race sometimes is the normal operating condition. * **Not something a wider client-side staleness window fixes.** The chain re-proves freshness at execution. Accepting older quotes on your side only buys more reverts. ### What to do about it **1. Obtain a NEW quote for every attempt** A retry that reuses the quote repeats the failure, because the quote is now older than it was. Each attempt draws its own quote, composes its own transaction, and signs again. A quote that is the same as the last one is not a new quote. ```ts theme={"dark"} import { ProgramRefusal, programErrorCode } from '@rekt-trading/1000x'; /** * Retry a quoted send. `attempt` must obtain a new quote and re-compose: it is a whole attempt, * not a resend. `slotMs` is `slotMs(config.params)`, read live. */ export async function withFreshQuote( attempt: () => Promise, slotMs: number, attempts = 3, ): Promise { let last: unknown; for (let i = 0; i < attempts; i += 1) { try { return await attempt(); } catch (e) { last = e; const code = e instanceof ProgramRefusal ? e.info.code : programErrorCode(e); // 6007 is the only code worth spinning on here. Everything else is a state or a bug. if (code !== 6007) throw e; // One slot, not a backoff. Waiting longer makes the next quote no fresher. await new Promise((r) => setTimeout(r, slotMs)); } } throw last; } ``` **2. Keep a wallet prompt out of the loop** If the retry re-signs through a person's wallet, every attempt spends seconds inside a budget of `market.maxOracleAgeSlots × config.params.slotMs`, and every attempt fails for the same reason, with one popup per failure. Keep the person off the signing path: `set_take_profit` is the one quote-carrying instruction the owner signs, and a [session key](/sdk/sessions) can sign it. **3. Check the quote before you sign it** A quote that is short of the market's floors cannot be admitted however fast it lands. Before signing, compare its distinct signers with `market.minSignatures` and its source count with `benchmarkSourceFloor(market, 'settle')`. `submitBenchmarkQuoted` refuses a short signer count before sending (`wire.signatures`), and `benchmarkQuoteView` carries the quote into the price gates, so a gate report renders the reason. **4. Tell the trader the truth** "Re-pricing…" is accurate and calm. "Trade failed" is neither. Surface a failure only after your attempts are exhausted, and say what happened: the price moved on before the transaction landed, and nothing was charged. ### Three failures, counted separately | Failure | What it looks like | What a retry does | | - | - | - | | **No quote** | the quote service refused or timed out | may succeed; count and alarm on it separately | | **The quote is too old** | a well-formed quote, past `maxOracleAgeSlots` when it lands | succeeds with a new quote | | **The quote is short** | a prompt quote below a market floor (signers or sources) | do not send it; obtain another | "I could not get a price", "the price I got was too old" and "the price I got cannot be admitted" need three different responses, and the third one must never reach `sendTransaction`. A short quote is not a refusal by the chain: nothing was sent. Say *"waiting for a fresh price"* and keep the control enabled. Reserve the word *refused*, and a disabled button, for a decision the program made. ## Which instructions carry a quote | Instruction | Carries a quote | Who signs | | - | - | - | | `open`, `add_collateral` | **no** | the owner, **or a session key they authorised** | | `request_close` | **no** | the owner, **or their session key** | | `mark_expiry` | **no** | **anyone**, from the deadline | | `settle` — `knockout`, `takeProfit`, `userExpiry`, `tenorExpiry`, `borrowSpent` | yes | **anyone** | | `settle` — `voluntary` | yes | **anyone**, once the owner has requested the close | | `settle` — `lastResort` | **no** | **anyone** | | `stamp_book` | yes | **anyone** | | `prove_price` (`provePrice`) | yes | **anyone** | | `set_take_profit` | yes | the owner, **or their session key** | | `fill`, and the proof forms of `void_open` and `reverse_add` | yes | **a listed filler only** | | `void_open`, `reverse_add` by timeout | **no** | **anyone** | | `init_trader_account`, `set_payout_destination`, `authorize_delegate`, `renew_delegate`, `revoke_delegate` | **no** | the owner | | `claim_payout` | **no** | **anyone**, to the recorded destination; the owner, to any other account | > [!NOTE] > > **The instructions a person signs to trade carry no price.** Setting up a session, funding an > account, opening, adding and asking for a close race nothing, so a wallet dialog is fine for them. > `set_take_profit` is the exception: the owner signs it and it carries a quote, so sign it with a > session key or locally. Settles and stamps are sent by anyone, and the venue's keepers send them. ## Closing a position The trader's Close is `request_close`, which carries no quote. The settle that completes it is sent by anyone with the window quote, and the venue's keepers do. So the freshness budget never reaches a person who only trades. * **A position that reaches its barrier, its rung or either clock does not need the trader.** Those four reasons are permissionless, so they land without the owner signing. Nobody is paid to submit them: what is permissionless is the right to close, not a reward. * **A trader's own timer** (`userTimerS` at open, zero or at least the venue's timer floor, 26 seconds by default) turns "close it at this time" into a clock that anyone may prove. Offer it. ## Related refusals | Error | Code | Retry | What it means | | - | - | - | - | | `NoFreshPrice` | 6007 | immediately | No quote cleared admission at execution. Obtain a new quote and resend. | | `BenchmarkQuoteMalformed` | 6178 | never | The quote could not be read: the Instructions sysvar is missing from the remaining accounts, the ed25519 instruction is not immediately before yours, or the payload is not the expected shape. | | `OracleFrozen` | 6190 | after-governance | The venue's oracle is frozen. Opens, adds, close requests, expiry marks, `stamp_book`, `lastResort` closes and the return of an order or add that needs a price refuse; every other settle and `set_take_profit` fail `NoFreshPrice`. Read `config.oracleFrozen`. | An open and an add carry no quote. The fill judges the first price instead, and a price that fails is a returned order (`OpenVoided`), not a refusal. At settle, a quote that fails any of these checks comes back as `NoFreshPrice`, never as its own code. If `NoFreshPrice` repeats on a settle, read `config.oracleFrozen` before you retry again. The full catalogue, with a cause and a fix for each, is in [error handling](/sdk/errors). > [card] [Session keys](/sdk/sessions) > > The session-key delegate the program provides: authorise, fund, sign, revoke. > [card] [Opening a position](/sdk/opening) > > Building the instruction, the first-trade account, sizing, and sending. # Read the protocol Source: https://docs.rekt.money/sdk/reading Read the protocol from a cluster, price an open before you send it, and see exactly what a trader would be charged. This page goes from an empty file to a priced, gated open — reading only, sending nothing. It is the sequence every client performs before it shows anyone a button. For a bot that also sends, start with the [Quickstart](/sdk/quickstart). > [!NOTE] > > Everything here is a **read**. No keys, no signatures, nothing spent. Sending is > [the next page](/sdk/opening). ## 1. Read the protocol Three accounts give a client what it needs to price an open: the config (every governed parameter), the vault (the pool), and one market per asset. Their addresses are derived locally, so you never have to trust an address printed on a web page. ```ts read-protocol.ts theme={"dark"} import { Connection, PublicKey } from '@solana/web3.js'; import { assetId, chainNowSeconds, configPda, decodeConfig, decodeMarket, decodeVault, marketPda, vaultGauges, vaultPda, type ConfigView, type MarketView, type VaultGauges, type VaultView, } from '@rekt-trading/1000x'; export interface Protocol { config: ConfigView; vault: VaultView; gauges: VaultGauges; market: MarketView; nowUnix: bigint; nowSlot: bigint; } async function mustRead(connection: Connection, address: PublicKey, what: string) { const info = await connection.getAccountInfo(address, 'confirmed'); if (!info) throw new Error(`${what} does not exist at ${address.toBase58()}`); return new Uint8Array(info.data); } export async function readProtocol(connection: Connection, symbol: string): Promise { const config = decodeConfig(await mustRead(connection, configPda().address, 'the config')); const vault = decodeVault(await mustRead(connection, vaultPda().address, 'the vault')); const market = decodeMarket( await mustRead(connection, marketPda(assetId(symbol)).address, `the ${symbol} market`), ); // The pool's gauges need the vault's own token balance, read from the account the vault names. const vaultToken = new PublicKey(Buffer.from(vault.tokenAccount, 'hex')); const balance = await connection.getTokenAccountBalance(vaultToken, 'confirmed'); const nowSlot = await connection.getSlot('confirmed'); // The chain's clock, never this machine's: the program judges against `Clock.unix_timestamp`. // `getBlockTime` on one recent slot can answer null or throw; `chainNowSeconds` walks back to a // slot that answers. const nowUnix = BigInt(await chainNowSeconds(connection)); return { config, vault, gauges: vaultGauges(vault, BigInt(balance.value.amount)), market, nowUnix, nowSlot: BigInt(nowSlot), }; } ``` > [!WARNING] > > **Never cache `config.params`.** Every field in it is governed and can move on chain without a > program upgrade. Re-read it, and show the reader how old your copy is. **Game slot fields of `MarketView`.** `decodeMarket` reads the market's game word. Each field is 0 on a market with no game terms. | Field | What it holds | | - | - | | `gameSlots` | Which fee-terms slots hold a game's terms: bit `slot - 1`. | | `sprintRegs` | The slot in force for game id 1 (bits 0 to 2; 0 means off) and the last one (bits 3 to 5). | `sprintCurSlot(market)` and `sprintPrevSlot(market)` return the slot in force for Sprint and the last one. A settle or a refund on a market with a non-zero `gameSlots` carries the market's `FeeTermsTable`, writable: `feeTermsTableFor(market, config, 'settle')` names it. ## 2. Read how the market is priced An instruction that reads a price carries a **signed quote inside the transaction**, not a price account you can read, so a read-only client has no price to fetch from the chain. What it can read is the shape of the market's oracle: which kind it is, and the floors a settle or a `stamp_book` must clear. ```ts read-oracle.ts theme={"dark"} import { benchmarkSourceFloor, settlementIdentity, type MarketView } from '@rekt-trading/1000x'; export function oracleShape(market: MarketView) { const identity = settlementIdentity(market); return { // 'benchmark' with `pull: true`: the price rides in the caller's own transaction. vendor: identity.vendor, pull: identity.pull, // The fewest distinct oracle signatures a quote must carry. minSignatures: market.minSignatures, // The fewest sources a quote must aggregate to settle. settleSources: benchmarkSourceFloor(market, 'settle'), // How many slots old a quote may be when the program reads it. maxAgeSlots: market.maxOracleAgeSlots, }; } ``` [Quotes and freshness](/sdk/quotes) is the reference for the quote itself: how a transaction carries it, and the checks the program applies. ## 3. Price the open before you offer it `openPreview` answers everything a trader needs to see, for the exact terms they are about to take, at the parameters currently in force. ```ts preview.ts theme={"dark"} import { openPreview, type ConfigView, type MarketView } from '@rekt-trading/1000x'; export function quote(config: ConfigView, market: MarketView, nowUnix: bigint) { // The fourth argument is the rung in basis points of stake: 20_000 is 2.00x, the floor below // which the protocol will not price a take-profit. A bare `2` here asks for 2 bps and refuses. const preview = openPreview(config, market, 1_000_000n, 20_000, nowUnix); return { collateral: preview.collateral, // what is at risk entryFee: preview.entryFee, // taken from inside the budget; 0 at an entry fee of 0 totalDebit: preview.totalDebit, // what actually leaves the wallet maxPayout: preview.maxPayout, // the gross payout at the target, before the exit fee and the share of the gain the terms withhold reserved: preview.reserved, // its maximum payout and closing fee; the pool sets aside only the stake barrierPayout: preview.barrierPayout, // what the trader receives at the barrier barrierMicroBp: preview.barrierMicroBp, takeProfitMicroBp: preview.takeProfitMicroBp, }; } ``` > [!NOTE] > > Show `barrierPayout` next to the confirm button, at the same visual weight as the payout you are > excited about — see [the venue](/venue#what-you-sign-on-an-open). A close between the entry and the > barrier pays what is left after the loss, less a loss tax on that loss and then the exit fee: see > [what a close pays](/sdk/positions#what-every-close-would-pay-right-now). ## 4. Ask what would refuse it Before you build a transaction, ask the SDK which gate would stop it. `openGates` evaluates the refusals the program raises for an open, in the program's order. > [!NOTE] > > An open carries no quote: the fill judges the price, and the price rows do not decide the order. > See [orders and closes](/sdk/orders). The checks a quote meets are in > [quotes and freshness](/sdk/quotes#what-the-program-checks). ```ts what-would-refuse.ts theme={"dark"} import { openGates, type GateReport, type OpenContext, type OpenRequest } from '@rekt-trading/1000x'; export function whatWouldRefuse(ctx: OpenContext, req: OpenRequest): GateReport { const report = openGates(ctx, req); if (report.refusal) { // `value` and `threshold` are already formatted for a human: // "stake $0.10" against "at least $0.20" console.log(`${report.refusal.label}: ${report.refusal.value} / ${report.refusal.threshold}`); console.log(report.refusal.detail); } return report; } ``` Building the `OpenContext` and rendering the whole table is [the next page](/sdk/gates). ## 5. Put it together ```ts summary.ts theme={"dark"} import { Connection } from '@solana/web3.js'; import { openPreview } from '@rekt-trading/1000x'; import { readProtocol } from './read-protocol'; import { oracleShape } from './read-oracle'; export async function summary(symbol: string): Promise { const url = process.env['SOLANA_RPC_URL']; if (!url) throw new Error('SOLANA_RPC_URL is not set'); const connection = new Connection(url, 'confirmed'); const p = await readProtocol(connection, symbol); const oracle = oracleShape(p.market); const preview = openPreview(p.config, p.market, p.config.params.minCollateral, 20_000, p.nowUnix); return [ `${symbol}: priced by ${oracle.vendor}, a settle needs ${oracle.settleSources} sources and ${oracle.minSignatures} signatures`, `pool: assets ${p.gauges.lpAssets}`, `open at minimum stake: debit ${preview.totalDebit}, max payout ${preview.maxPayout}`, ].join('\n'); } ``` ## Where each value is read | Value | Where | | - | - | | Stake limits | `config.params.minCollateral`, `config.params.maxCollateral` | | Fees | `config.params.entryFeeBps`, the market's fee-terms account (`feeTermsTablePda`), `config.params.borrowRateBpsPerHour` | | Leverage | `market.tier` and `config.minTier` | | Payout cap | `config.params.payoutCapMultiple` | | Tenor | `config.params.tMaxSeconds`, frozen onto a position when it opens; on gold, `market.sessionBufferS` also ends a position's life before its session closes | | Loss tax | `config.params.lossTaxBps`, frozen onto a position when it opens | | Minimum hold | `config.minHoldSlots` | | Whether closes are stopped | `config.oracleFrozen`, `config.settlesDisabled` | ## What you have, and what you do not You now have every number a trader needs to decide, read from chain rather than typed, and every refusal that could stop the trade, before you send anything. What you do not have yet is a signature. An open, an add and a close request carry no price, so there is no quote to obtain for them: see [orders and closes](/sdk/orders). A settle, a `stamp_book` and `set_take_profit` carry a signed quote in the same transaction, and a quote's age is judged **at execution**, against a governed bound of a small number of slots. Who signs, and how fast, decides whether one of those lands at all. Read [session keys](/sdk/sessions) before you write the send path. > [card] [Session keys](/sdk/sessions) > > Who signs a trade, and how the program's session-key delegate works. > [card] [Quotes and freshness](/sdk/quotes) > > What a quote is, why `6007` happens, and how to handle it without lying to the trader. > [card] [Reading gates](/sdk/gates) > > Build the context, render the table, and explain a refusal properly. > [card] [Opening a position](/sdk/opening) > > Build the order, size it, simulate, send, and read its sequence number. # Reference Source: https://docs.rekt.money/sdk/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 215 ms a slot (`SLOT_MS`). The program bounds the first by > `market.maxOracleAgeSlots` and the second by `market.maxOracleAgeMs`. See > [quotes](/sdk/quotes#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](/sdk/orders#the-timing-settings). | | **Pool gauges** | `vaultGauges` | | **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`, `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`, `freePositionSlots`, `fetchFreePositionSlots`, `freeRoundSlots`, `fetchFreeRoundSlots`, `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`, `refusalOf`, `refusalFromLogs`, `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](/sdk/settling#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, DEFAULT_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: DEFAULT_POSITION_SLOTS, // the default, 12; a client may ask for 1..=21 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](/how-it-works#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](/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 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](/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. ## 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; 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](/sdk/sessions) > > Who signs a trade, and the session-key delegate's three clocks. > [card] [Risk disclosure](/risk) > > What can go wrong, for traders and for the liquidity pool. # Session keys Source: https://docs.rekt.money/sdk/sessions A scoped, revocable key that signs trades with no wallet prompt: who signs a trade, how to authorise, fund, use, renew and revoke a session key, how to gate before you send, and what a leaked key costs. An `open`, an `add_collateral` and a `request_close` carry no quote, so a person can approve each one in a wallet. A **session key** removes the prompt on every trade: the trader authorises a short-lived, scoped, revocable key once, and that key then signs locally. This page says who can sign a trade, and documents the session key the program provides. The instructions that carry a quote are `set_take_profit`, and any `settle`, `stamp_book` or `prove_price` a client sends itself. A quote ages out in slots, so a person reading a wallet dialog cannot land one of those: sign it locally. Read [quotes](/sdk/quotes) for the age rule. ## Who can sign a trade Who signs is an integration decision, and there is more than one reasonable answer. Weigh them for your own product. > [card] Your service signs > > Your own backend holds, or is delegated, the authority to sign and signs each trade > programmatically with no per-trade prompt. You choose the custody model and where the key lives. > Whatever signs holds that authority for as long as it holds the key. > [card] A scoped delegate > > The program provides a **session-key delegate**: the trader authorises a short-lived, scoped, > revocable key once, and that key then signs locally with no dialog. The rest of this page is its > reference. > [card] The trader signs each > > The trader approves every open, add and close request in their wallet. None of them carries a > quote, so each is a single attempt and no clock runs against the prompt. The cost is a prompt on > every trade. > [!NOTE] > > Whichever you choose, the program checks the signer. The pages on [opening](/sdk/opening), > [orders and closes](/sdk/orders) and [reading gates](/sdk/gates) do not assume a particular signing > model. Gas is a separate decision: see [who pays the fee](#who-pays-the-fee). ### Who pays the fee A Solana transaction has a **fee payer**, and the fee payer signs. That gives you a second axis, independent of who signs the trade: * **The user pays their own fee.** Simplest, but the user needs lamports on the key that pays. In the delegate model below that is the delegate key, not the wallet. * **You sponsor the fee.** A fee payer you control is added to the transaction so the user needs no SOL. How you fund it is your choice. The fee payer does not have to be the key that signs the trade. Placing it on a human wallet puts the prompt back on every trade. ## The program's option: a session-key delegate The program provides a `TradeDelegate`: a short-lived, scoped, rate-limited key that the trader authorises once and that then signs locally with no dialog. If you take this route, the human is out of the trading path. > [card] It never holds funds > > The money stays in the trader's own token account. The trader grants an SPL allowance to the > trader's own delegate account (`delegatePda(owner)`), not to the session key, and only the program > spends it, inside its own instructions. The key holds no token authority: it cannot send a token > `Transfer`. What a leak can cost is on > [what a leak costs](#what-a-session-key-costs-you-if-it-leaks). > [card] Its trading has a hard deadline > > An absolute expiry on the `TradeDelegate`, 24 hours by default and 7 days at most, after which > the key can neither open, close nor fund here. The program spends the allowance only for a live > session, so the expiry ends the key's spending too. The SPL approval itself stands until it is > revoked: revoke on logout. > [card] Its trading has a spend rate > > A decaying budget per window on what the key may OPEN here, metered on the open's `budget`: the > fee-inclusive total, the money actually at risk. It does not meter the SPL allowance, and by > default it equals the allowance, so it is not what bounds a leak. > [card] It is revocable, with one exception > > One instruction, effective in the same slot, and it returns the account's rent. > > **The exception:** if the USDC account the allowance was granted over is frozen, closed, or has > been handed to somebody else, the program cannot clear the approval. It ends the session, and the > allowance survives and comes back the moment the account works again. Clearing it then takes its > own signature against that account. > > The token account is a **required** account on the revoke: pass `TradeDelegate.tokenAccount`, > read off the chain. > [!NOTE] > > **The session key is not an SPL delegate.** Authorising a session approves the trader's own > delegate account, `delegatePda(owner)` (seeds `["delegate", owner]`), for the allowance on the > trader's token account, under the trader's own signature. Only the program can sign for that > account, and it signs only inside its own trading instructions (`open`, `add_collateral`) and > `session_fund`, after it checks that the session key signed, that the session is live, and that the spend fits > the window. It always spends from the token account the session was authorised over > (`WrongDelegateTokenAccount`, 6122, for any other). `renewSession` approves the same account again. > [!WARNING] > > **An approval that names the session key itself still behaves the old way.** If the token > account's delegate slot holds the session key (an approval granted directly to the key), the key > can sign an SPL `Transfer` of the remaining allowance to any account, with this venue not in the > path. The program still trades on such an approval until the session expires. One owner signature > ends it: `renewSession` moves the approval to the delegate account, and `endSession` clears it. > Offer one of the two to any trader whose slot holds the key. ## Using the delegate, step by step It is five moves. The funding step is the one most often skipped: a session that authorises correctly and then cannot send anything. **1. Generate a session key in the client** An ordinary keypair, created where the trades will be signed. It is not the trader's wallet and must never be derived from it. ```ts session.ts theme={"dark"} import { Keypair } from '@solana/web3.js'; /** * Generate it here. **WRITE THE SECRET BEFORE YOU SEND THE AUTHORISATION** — step 2 — and * remove it only on a decoded REFUSAL, never on an unknown. * * Scope the storage to the session and clear it on logout, at which point you also call * `endSession` (step 5). A session key in durable storage outlives the trader's intent. */ export const sessionKey = Keypair.generate(); ``` > [!WARNING] > > **Persist the secret BEFORE the authorisation is sent, not after it is confirmed.** A key stored > for an authorisation that never landed costs 64 unused bytes. A key discarded for an > authorisation that did land leaves the chain holding a `TradeDelegate` naming a public key whose > secret exists nowhere, with the session's fuel SOL on it and a standing SPL approval on the > trader's USDC. A confirmation poll that times out on a transaction that landed produces exactly > that. > > **Remove the stored key only on a decoded refusal.** A blockhash expiring does not tell you > whether a transaction was accepted, so a send you could not confirm must keep the key. See > [the failures that are not the program's](/sdk/errors#errors-that-are-not-the-programs). **2. Authorise it — one transaction, one wallet prompt, ever** `authorizeSession` builds the authorisation. **One instruction sets all three limits**: the expiry, the spend window, and the SPL token allowance. The program performs the SPL `approve` itself, so the half the token program enforces cannot go missing. ```ts authorise.ts theme={"dark"} import { Connection, Keypair, PublicKey, Transaction } from '@solana/web3.js'; import { DEFAULT_SESSION_TERMS, authorizeSession, configPda, delegatePda, ourInstruction, toHex, } from '@rekt-trading/1000x'; export async function authorise(args: { connection: Connection; owner: PublicKey; /** The trader's own USDC account. The allowance is written against THIS account. */ traderToken: PublicKey; sessionKey: Keypair; /** How much this session may spend in total before it must be renewed. */ allowance: bigint; sign: (tx: Transaction) => Promise; }): Promise { const built = authorizeSession({ owner: toHex(args.owner), delegateKey: toHex(args.sessionKey.publicKey), delegate: toHex(delegatePda(args.owner).address), traderToken: toHex(args.traderToken), // Required: the program reads the governed maximum stake off the config account. config: toHex(configPda().address), // 24 hours, a 24-hour spend window, and the window's ceiling. Override deliberately. terms: DEFAULT_SESSION_TERMS, // Required, with no default. `0` grants Close and Retarget; `DELEGATE_NO_CLOSE` withholds both. restrictions: 0, // The SPL allowance is a TOTAL that draws down and never refills. Size it for how long // the trader means to be at the desk; the window limit only bounds the rate. allowance: args.allowance, }); const tx = new Transaction().add(...built.map(ourInstruction)); tx.feePayer = args.owner; tx.recentBlockhash = (await args.connection.getLatestBlockhash('confirmed')).blockhash; // The ONE wallet prompt in the whole arrangement. The trader may take as long as they like // reading it. const signed = await args.sign(tx); // STORE THE SECRET HERE, before the send — not after a confirmation. See step 1. persistSessionSecret(args.owner, args.sessionKey.secretKey); return args.connection.sendRawTransaction(signed.serialize()); } ``` > [!WARNING] > > **The chain holds a delegate and this device does not hold its key — what now?** It is the > state a confirmation timeout produces. The recovery is **`endSession`** (step 5): it closes the > delegate account, drops the SPL allowance, is signed by the *trader* rather than by the lost > key, and returns the rent. Then start a new session. The lost key's SOL cannot be recovered. > [!NOTE] > > Show the trader what they are signing: the expiry, the per-window ceiling and the allowance, in > dollars. This transaction is the whole of the authority they are handing over, and it is the > only moment they get to look at it. **3. Fund it — the session pays its own fee** If the *owner* pays the fee, the owner signs, and the wallet prompt is back on every trade. So on this route the fee is paid by a key that is not the human: the session key itself (shown here), or a separate sponsoring fee payer you add to the transaction (see [who pays the fee](#who-pays-the-fee)). Either way it needs lamports. The simplest shape funds the session key in the same moment you authorise it. ```ts fund.ts theme={"dark"} import { LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction } from '@solana/web3.js'; /** * Enough SOL for the session's own transaction fees. Send it alongside the authorisation so a * trader signs once for both. * * Return the remainder to the owner when you revoke — a session key that keeps a dust balance * after logout is a wallet nobody is watching. */ export function fundSession(owner: PublicKey, sessionKey: PublicKey, sol = 0.01): Transaction { return new Transaction().add( SystemProgram.transfer({ fromPubkey: owner, toPubkey: sessionKey, lamports: BigInt(Math.round(sol * LAMPORTS_PER_SOL)), }), ); } ``` > [!WARNING] > > A session that is authorised but unfunded fails at the network layer, before any of this > protocol's refusals are reached, so none of the gate reports on these pages will explain it. > Check the session key's lamport balance at start-up and top it up before it reaches zero. **4. Sign every trade with the session key** The session **signs and pays**. The book, the token account and the money all stay the owner's: `authority` is whoever signs, and `delegate` names the session's account so the program can check it. ```ts trade-with-session.ts theme={"dark"} import { ComputeBudgetProgram, Connection, Keypair, PublicKey, TransactionMessage, VersionedTransaction, } from '@solana/web3.js'; import { assetId, computeUnitLimit, configPda, delegatePda, ix, marketPda, ourInstruction, priceAccountsFor, toHex, traderPda, vaultPda, type ConfigView, type MarketView, } from '@rekt-trading/1000x'; export async function openWithSession(args: { connection: Connection; config: ConfigView; symbol: string; market: MarketView; /** The trader. Signs NOTHING here. */ owner: PublicKey; /** The session. Signs and pays. */ sessionKey: Keypair; traderToken: PublicKey; vaultToken: PublicKey; protocolToken: PublicKey; /** The fee-inclusive TOTAL to spend. The debit is at most this. */ budget: bigint; direction: 'long' | 'short'; rungBps: number; userTimerS: number; /** The mandatory floor on the position SIZE — `sizeForTotal(budget, config.params).collateral`. * `0n` is refused (`MinCollateralOutRequired`). */ minCollateralOut: bigint; /** A durable key you choose, or `0n`. Read by nothing on chain. */ openerTag: bigint; }): Promise { const built = ix.open( { // Whoever signs. With a session that is the session key, not the owner. authority: toHex(args.sessionKey.publicKey), trader_token: toHex(args.traderToken), config: toHex(configPda().address), market: toHex(marketPda(assetId(args.symbol)).address), vault: toHex(vaultPda().address), vault_token: toHex(args.vaultToken), protocol_token: toHex(args.protocolToken), // The OWNER's book, always. The session never gets one of its own. positions: toHex(traderPda(args.owner).address), // `null` here with a signer who is not the owner is refused by the program, so this // cannot be used to open against somebody else's book. delegate: toHex(delegatePda(args.owner).address), }, { // Fee-inclusive TOTAL; the venue takes its fee from inside it. budget: args.budget, direction: args.direction === 'long' ? 0 : 1, rung_bps: args.rungBps, user_timer_s: args.userTimerS, // Mandatory floor on the position SIZE. Set it to `sizeForTotal`'s predicted collateral, // never a token value; `0n` is refused. min_collateral_out: args.minCollateralOut, referrer: null, // `0` is the market's own tier, 1000x: see `/sdk/opening`. The tier is a property of the // trade, so a session key and the owner pass the same value. tier: 0, // A durable key you choose, read by nothing on chain. `0n` is the absence. opener_tag: args.openerTag, }, // The market's fee-terms account when it has terms. An order carries no quote. priceAccountsFor(args.market, args.config, 'open'), ); const { blockhash } = await args.connection.getLatestBlockhash('confirmed'); const message = new TransactionMessage({ // The session pays. An owner fee payer means an owner signature means a wallet prompt. payerKey: args.sessionKey.publicKey, recentBlockhash: blockhash, instructions: [ ComputeBudgetProgram.setComputeUnitLimit({ units: computeUnitLimit('open') }), ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1_000 }), ourInstruction(built), ], }).compileToV0Message(); const tx = new VersionedTransaction(message); tx.sign([args.sessionKey]); // Simulate first, as on /sdk/opening: a refusal costs nothing and arrives as a name. const sim = await args.connection.simulateTransaction(tx, { commitment: 'confirmed' }); if (sim.value.err !== null) throw new Error(JSON.stringify(sim.value.err)); return args.connection.sendTransaction(tx); } ``` **5. Revoke on logout** `endSession` closes the delegate account **and** drops the SPL allowance, in one instruction signed by the trader. It takes effect in the same slot and returns the account's rent, so revoking costs less than nothing. ```ts revoke.ts theme={"dark"} import { Connection, PublicKey, Transaction } from '@solana/web3.js'; import { decodeTradeDelegate, delegatePda, endSession, ourInstruction, toHex } from '@rekt-trading/1000x'; export async function revoke(args: { connection: Connection; owner: PublicKey; sign: (tx: Transaction) => Promise; }): Promise { const address = delegatePda(args.owner).address; const info = await args.connection.getAccountInfo(address, 'confirmed'); // No account is not an error — it is a trader with no session, which is the goal state. if (!info) return null; const delegate = decodeTradeDelegate(new Uint8Array(info.data)); const built = endSession({ owner: toHex(args.owner), delegate: toHex(address), // MUST be the account the allowance was granted over. `TradeDelegate.tokenAccount` is // pinned by the chain — read it rather than re-deriving the trader's associated token // account and hoping the two agree. traderToken: delegate.tokenAccount, }); const tx = new Transaction().add(...built.map(ourInstruction)); tx.feePayer = args.owner; tx.recentBlockhash = (await args.connection.getLatestBlockhash('confirmed')).blockhash; const signed = await args.sign(tx); return args.connection.sendRawTransaction(signed.serialize()); } ``` > [!NOTE] > > Revoke on logout, on wallet disconnect, and on tab close if you can reach it. Also revoke > when the trader asks: put the control somewhere they can find it, showing the expiry and the > remaining allowance. ## Gate before you send Three separate clocks can stop a session, and only two of them belong to this program. Check all three before you build a transaction. A refusal predicted costs nothing; a refusal discovered costs a fee and a confusing failure. ```ts session-gates.ts theme={"dark"} import { decodeTradeDelegate, delegateGates, delegatePda, sessionAllowanceGates, sessionState, toHex, type GateReport, } from '@rekt-trading/1000x'; import { Connection, PublicKey } from '@solana/web3.js'; export async function sessionReports(args: { connection: Connection; owner: PublicKey; sessionKey: PublicKey; traderToken: PublicKey; collateral: bigint; nowUnix: bigint; }): Promise<{ authority: GateReport; allowance: GateReport; expiresInS: number }> { const info = await args.connection.getAccountInfo(delegatePda(args.owner).address, 'confirmed'); const delegate = info ? decodeTradeDelegate(new Uint8Array(info.data)) : null; // The SPL allowance is the clock NO account of this program can see. Read it from the token // account itself. Pass `null` if you could not: `sessionAllowanceGates` then refuses to report // green, because an unread limit reported as green is how this arrangement fails quietly. const parsed = await args.connection.getParsedAccountInfo(args.traderToken, 'confirmed'); const data = parsed.value?.data; const allowance = data && 'parsed' in data ? BigInt(data.parsed.info.delegatedAmount?.amount ?? '0') : null; const ctx = { delegate, owner: toHex(args.owner), signer: toHex(args.sessionKey), nowUnix: args.nowUnix, allowance, }; return { authority: delegateGates(ctx, args.collateral), allowance: sessionAllowanceGates(ctx, args.collateral), expiresInS: delegate ? sessionState(delegate, args.nowUnix).expiresInS : 0, }; } ``` ### The three clocks | Clock | Who enforces it | How it ends | How you restore it | | - | - | - | - | | **Expiry** | this program | an absolute deadline, 24 hours by default | `renewSession` — one trader signature | | **Spend window** | this program | a decaying budget per window, so it refills continuously rather than resetting on a boundary | wait, or `renewSession` with a higher limit | | **SPL allowance** | the SPL Token program | a **total** that draws down and never refills | `renewSession`, which carries the `approve` with it | > [!WARNING] > > **The allowance is the one that will surprise you.** A long-running session usually stops not > because it expired and not because it hit its per-window ceiling, but because the SPL allowance > reached zero. That refusal arrives from the *token program* as `InsufficientFunds`, carrying none > of this program's error shape. It reads to a trader as the venue being broken. > > The rule that removes the edge: **renew the session and the allowance together, always.** > `renewSession` does exactly that in one instruction. ```ts renew.ts theme={"dark"} import { DEFAULT_SESSION_TERMS, configPda, delegatePda, renewSession, toHex } from '@rekt-trading/1000x'; import { PublicKey } from '@solana/web3.js'; /** Renew well before the deadline — a session that expires mid-trade fails the trade, not the tick. */ export function buildRenewal( owner: PublicKey, sessionKey: PublicKey, traderToken: PublicKey, /** Read off `TradeDelegate.restrictions` — a renewal re-states the byte rather than keeping it. */ restrictions: number, ) { return renewSession({ owner: toHex(owner), delegateKey: toHex(sessionKey), delegate: toHex(delegatePda(owner).address), traderToken: toHex(traderToken), config: toHex(configPda().address), terms: DEFAULT_SESSION_TERMS, restrictions, }); } ``` > [!WARNING] > > **`restrictions` is an argument, not a default.** A renewal re-states the byte: `renewSession` > writes what it is given, so a hardcoded `0` returns a Close button to a session that had it > withheld. Read it off `TradeDelegate.restrictions` and pass it back. ## The byte wall A session open costs about **128 bytes** more than an owner-signed one: the `TradeDelegate` account (32 B), the session's own signature (64 B) and its pubkey in the account list (32 B). An order carries no quote, so it still fits Solana's 1,232-byte packet with room to spare. A wrapped open names Minute's accounts as well as the venue's, and an instruction that carries a quote (a keeper's `settle`) carries the quote too: those compose a v0 message with the market's address lookup table. Measure your real byte count with a signed transaction before you send it. > [!WARNING] > > **1,232 bytes is a hard limit for a client built on `@solana/web3.js` v1.** The library serialises a > message into a buffer of exactly that size. A larger transaction throws `ERR_OUT_OF_RANGE` locally > and **never reaches the network**, so there is nothing to observe on chain and no error code to > catch. Keep every transaction within 1,232 bytes; the lookup table is the way. Choose the lookup table with `chooseMarketTable`. It tries the market's own table when the SDK names one, then the shared table `SHARED_KIND2_TABLE`, and returns the first one that passes the SDK's check. It never skips a market for want of a table. Every table is frozen: nobody can change what it resolves. A new table address reaches you in an SDK release, and `chooseMarketTable` picks it up. Read a table's contents once and cache them by address for the life of your process. Pass as `required` the protocol accounts your transaction names: `config` and `vault` (from the SDK's `configPda()` and `vaultPda()`) and, if you read it, `vault_token`. Pass `protocol_token` (`config.treasury`) as `rotatable`, never in `required`: the treasury can change after a table is frozen, and a table that lacks it costs 31 bytes and a warning, never the table. Never pass a trader's or a position's account. ```ts lookup-table.ts theme={"dark"} import { Connection, PublicKey } from '@solana/web3.js'; import type { AddressLookupTableAccount } from '@solana/web3.js'; import { chooseMarketTable, configPda, vaultPda } from '@rekt-trading/1000x'; /** Contents by table address. A frozen table never changes, so this cache never goes stale. */ const cache = new Map(); export async function marketTable( connection: Connection, marketAddress: PublicKey, treasury: PublicKey, // config.treasury, from your own config read ): Promise { const chosen = await chooseMarketTable({ market: marketAddress, // The protocol accounts this transaction names. Never a trader's or a position's account. required: [ { name: 'config', address: configPda().address }, { name: 'vault', address: vaultPda().address }, ], // Can change after a table is frozen: a warning when a table lacks it, never a refusal. rotatable: [{ name: 'protocol_token', address: treasury }], fetchTable: async (address) => { const hit = cache.get(address.toBase58()); if (hit !== undefined) return hit; const got = (await connection.getAddressLookupTable(address, { commitment: 'confirmed' })).value; if (got !== null) cache.set(address.toBase58(), got); return got; }, }); // Bytes, never a refusal: an account composed as a static key, or the shared table in for a market's own. for (const note of [chosen.standIn, ...chosen.warnings]) if (note !== null) console.warn(note); return chosen.table === null ? [] : [chosen.table]; // []: compose legacy, and measure it with dryRun: true } ``` > [!NOTE] > > A market's own table must contain that market and every `required` account. The shared table does > not contain the markets it serves: a `required` account it lacks composes as a static key (+31 B). > If you check a table yourself instead of calling `chooseMarketTable`, call > `marketTableCheckSized({ market, address, table, required, shared })` on each of > `marketTableCandidates(market)`, and hold each > table to its own size. One minimum for every table refuses a good table. > [!NOTE] > > `submitBenchmarkQuoted`, the sender for instructions that carry a quote, refuses a lookup table on a > legacy message rather than dropping it silently. Measure your real byte count with `dryRun: true`: > it builds and signs exactly what would be sent, and sends nothing. ## Closing: a session key can do it > [!WARNING] > > **A session key CAN request a close, and it can move a take-profit target**, unless its grant > carries `DELEGATE_NO_CLOSE`. > > `request_close` and `set_take_profit` share one authoriser, so a session key authorised for the > position reaches both. The settle that completes a requested close is sent by anyone, and every > other close reason (knockout, take-profit, the two expiries, `lastResort` and `borrowSpent`) is > permissionless and needs no signature from the trader at all. > > A grant with `DELEGATE_NO_CLOSE` cannot request a close and cannot move a target. ## What a session key costs you if it leaks The arrangement is deliberately **weaker** than signing each trade with the wallet. State this to yourself plainly before you ship: * **The exposure is what the program lets a session do, until it expires.** A leaked key can open positions and add to them, up to the window budget per window and the remaining allowance in total, until the expiry. It can move USDC with `session_fund` only into the owner's own custody in a game the venue has enabled. **It cannot send the allowance anywhere else**: the SPL approval names the trader's delegate account, and only the program signs for it. Every payout goes to the payout destination on the book. The budget decays over the window, so in one window the key can spend up to twice the window limit. * **An approval that names the key itself is the old exposure.** Until the owner renews or ends the session, the key can move the remaining allowance with one SPL `Transfer`. See the warning [above](#the-programs-option-a-session-key-delegate). * **It CAN close a position and CAN move a take-profit target, unless you withhold that.** A leaked key can close a trader out at a moment the attacker chooses, or move a position's target. Size the session for it. Pass `restrictions: DELEGATE_NO_CLOSE` to `authorizeSession` and the session can neither close nor retarget (`DelegateMayNotClose`, 6156). **Passing `0` grants close and retarget.** `restrictions` is required on `authorizeSession` and on `renewSession`; omitting it is a build error, and with the types erased it throws. **A renewal re-states the byte rather than keeping it**: renew a session with `0` and you have granted it a Close button. Read the current value off `TradeDelegate.restrictions` (`sessionStanding` returns it as `restrictions`) and pass it in. The raw instructions `authorize_delegate` and `renew_delegate` take `(duration_s, window_seconds, window_limit, allowance, restrictions)`. Bit 1 of `restrictions` is accepted and does nothing. Any other bit is refused (`DelegateRestrictionUnknown`, 6157), so check `DELEGATE_RESTRICTIONS_KNOWN` before you send. The owner is never restricted by this: a trader signing with their own wallet can close, unless a guardian stop is set (`config.settlesDisabled`, or `config.oracleFrozen`, which leaves a priced close no price). * **Revoking clears both halves.** `endSession` ends the session and withdraws the SPL approval in the same instruction, so revoke rather than waiting for expiry. **Expiry ends what the key can spend and does not withdraw the approval**, which then names a closed delegate account until it is revoked. If the trader's token account was frozen or closed when you revoked, send a bare SPL `revoke` against it once it is usable again. * **Settlement proceeds cannot be redirected.** A settle pays the destination recorded on the book, and no session key can change that record. * **A session key cannot authorise another delegate.** That still needs the owner. * **Size the allowance for the session, not for the year.** The SDK's default is `DEFAULT_DELEGATE_WINDOW_LIMIT`, **\$1,000** (`allowance ?? terms.windowLimit`). A large allowance to save a renewal prompt trades the trader's money for your convenience. A small one has a cost too: a trader who exhausts it meets a wallet prompt at exactly the moment the session existed to remove one. **Pass `allowance` explicitly.** The window limit is a per-window rate ceiling and the allowance is a lifetime total: they are two different numbers. * **Revoke on logout.** It is one instruction, it is instant, and it refunds rent. ## Tell what state a session is in, from the chain Two accounts, and one call. **1. Read the delegate PDA** `delegatePda(owner)` — seeds `[b"delegate", owner]`, one per trader. `decodeTradeDelegate` gives you `expiresAt`, `delegate`, `windowLimit`, `windowSpent`, `windowSince`, `restrictions` and `tokenAccount`. **2. Read TradeDelegate.tokenAccount, and never a guess** `revokeDelegate` pins its `trader_token` to that exact address and refuses any other with `WrongDelegateTokenAccount` (6122). `decodeTokenDelegate` reads the SPL side of it: the account's state, its delegate slot, and the allowance still standing. **3. Ask for the standing** `sessionStanding` names the combination, because the combination is what decides what to do. ```ts sessions-state.ts theme={"dark"} import { chainNowSeconds, decodeTradeDelegate, delegatePda, sessionStanding, unhex } from '@rekt-trading/1000x'; import { PublicKey } from '@solana/web3.js'; const [pda] = await connection.getMultipleAccountsInfo([delegatePda(owner).address]); const view = pda ? decodeTradeDelegate(new Uint8Array(pda.data)) : null; const [tok] = view ? await connection.getMultipleAccountsInfo([new PublicKey(unhex(view.tokenAccount))]) : [null]; const standing = sessionStanding({ delegate: view, tokenAccount: tok ? new Uint8Array(tok.data) : null, // The chain's clock: the program judges a session's expiry against `Clock.unix_timestamp`. nowUnix: BigInt(await chainNowSeconds(connection)), }); ``` | `kind` | the delegate | the SPL approval | `action` | | - | - | - | - | | `none` | no account | none | nothing to do | | `active` | live | live, to the trader's delegate account (or, on an older approval, to this key) | `resume` | | `allowance-exhausted` | live | spent or cleared | `renew` | | `displaced` | live | live, to **another program's key**: neither the trader's delegate account nor this key | `renew` | | `expired-approval-live` | **expired** | **live** | `revoke` | | `expired` | expired | gone | `revoke` | | `orphaned-approval` | **no account** | live | `revoke-spl-only` | | `frozen` | either | unreachable | `revoke`, then a bare SPL `revoke` after the thaw | | `unknown` | — | **not read** | read it | > [!WARNING] > > **`expired-approval-live` is the state to alert on, and no error code will tell you about it.** > The venue side has a clock; the SPL approval does not, and an expiry does not close the account. > A trade attempted by an expired key is refused with `DelegateExpired` (6108), which reads as > *renew and carry on* and says nothing about a standing authority over the trader's USDC. > > Pass `tokenAccount: null` for an account you read and found closed. Leave it `undefined` only > when you have genuinely not looked: `sessionStanding` then answers `unknown` rather than > calling the session active. > [!NOTE] > > **A token account holds one delegate slot.** SPL Token's `approve` writes it unconditionally, so > any other program the trader approves takes it from this session, with nothing emitted. The > session keeps passing every gate this program can check and fails inside the token program on the > next open. `sessionStanding` reports it as `displaced`; a renewal takes the slot back. A slot that > holds the trader's own delegate account, `delegatePda(owner)`, is this session's approval, not a > displacement. ## Funding a game from a session: `session_fund` A live session can move USDC from the trader's token account into the trader's **own custody in a game the venue has enabled**, with no wallet prompt. The program signs the transfer as the trader's delegate account, under the same window budget as an open. It refuses any other destination (`SessionFundDestinationRefused`, 6349). * **Accounts:** the session key (signer), the trader's token account (the one the session was authorised over), the trader's `TradeDelegate` (writable), the destination custody (writable), the governance table, the clock sysvar and the token program. * **Arguments:** `amount`, `game`, `player_bump`, `custody_bump`. Game 0 is Minute: the custody is `minutePlayerTokenPda(minutePlayerPda(owner))`, and the two bumps are the canonical bumps of the player and of the custody. * **Build it** with `ix.sessionFund(accounts, args)`, and declare `computeUnitLimit('session_fund')`. * **Minute is enabled.** Governance can switch a game off and on. A game the venue has no entry for cannot be enabled. * **Refusals:** the session refusals below (`DelegateExpired`, `DelegateWindowLimitReached`, `NotTheDelegate`, `DelegateMayNotSign`), `WrongDelegateTokenAccount` (6122) for another token account, and 6349 for any other destination, a wrong bump, an unknown game or a game switched off. A zero amount is refused. Minute's session round instructions call `session_fund` for you: see [integrating Minute](/minute/integrating#who-pays-and-who-may-sponsor). ### The four pathways | pathway | send | who signs | cost | when | | - | - | - | - | - | | **resume** | nothing | — | nothing | `kind: 'active'` | | **renew** | `renewSession` | the **trader**, never the key | one signature, rent unchanged | expired, budget bound, allowance spent, approval displaced, or the key must be rotated | | **close and reopen** | `endSession`, then `authorizeSession` | the trader, twice | two signatures; rent returned then re-paid | you are changing the token account — a renewal may not move it (`DelegateTokenAccountMayNotChange`, 6137) | | **revoke** | `endSession` | the trader | **less than nothing** — the account closes to the trader and returns its rent | logout, a leaked key, or any expired session | * **A renewal resets the spend meter and re-states `restrictions`.** Read the current byte off `TradeDelegate.restrictions` and pass it back; `0` is not *unchanged*, it is *this session may close positions*. * **A renewal re-approves the SPL allowance in the same instruction**, so it is the fix for an exhausted or displaced approval as well as for an expiry. * **Rotating a leaked key is a renewal, not a reopen.** `renewSession` takes a different `delegateKey`, and the approval moves to it in the same instruction. * **`endSession` is safe on a session that already expired, and safe to send twice.** ## The refusals a session meets None of these appear in `openGates`: the program checks them very early, before the other gates in that report. `delegateGates` predicts the first four; read it. | Error | Code | Retry | What it means, and the fix | | - | - | - | - | | `DelegateExpired` | 6108 | never | The absolute deadline passed. Do not retry with this key. The trader sends `renewSession`, or signs the request directly. | | `DelegateWindowLimitReached` | 6109 | after-state-changes | This window's ceiling is used up. The budget decays continuously, so waiting works, or renew with a higher limit. | | `NotTheDelegate` | 6110 | never | The signer is not this trader's authorised key. Re-authorise. | | `DelegateMayNotSign` | 6115 | never | The owner signed **and** passed the delegate account. Pass `delegate: null` when the owner signs for themselves. | | `DelegateMayNotClose` | 6156 | never | The session's grant carries `DELEGATE_NO_CLOSE`, and this was a close or a retarget. The owner may close with their own signature, unless a guardian stop is set (`config.settlesDisabled`, or `config.oracleFrozen`, which leaves a priced close no price). | And one that is not this program's at all: `InsufficientFunds` from the SPL Token program, when the allowance is exhausted. `sessionAllowanceGates` is the only thing that predicts it. ## Where to go next > [card] [Quotes and freshness](/sdk/quotes) > > What a quote is, why a settle can be refused with `6007`, and what to do about it. > [card] [Opening a position](/sdk/opening) > > The transaction shape, the two hard walls, and building the instruction. > [card] [Reading gates](/sdk/gates) > > Every protocol refusal, before you send, with its measured value. > [card] [Error handling](/sdk/errors) > > The full catalogue, and whether retrying can ever help. # Settling a position Source: https://docs.rekt.money/sdk/settling Choosing the reason, checking the gates the engine cannot see, and building the close. Settlement is permissionless, and it pays its submitter nothing. Every close except a voluntary one is **provable by public information**: the two price reasons by the price, the two expiries by the clock, the funding reason by the price and the funding owed, and the no-price backstop by the clock and the absence of a price. So anyone can submit them. A voluntary close starts with the owner's `request_close`, and the settle that completes it is open to anyone too: see [request or mark, then settle](#request-or-mark-then-settle). **Submitting one pays you nothing.** No fee, no share of the settlement, no gas rebate: budget the SOL as a cost. Anyone may submit a close, and nobody is paid for it. > [!NOTE] > > **On a feed-kind-3 market (`isKind3Market(market)`) the venue's keepers settle.** Its priced > instructions carry a signed tick and the market's own accounts, not a quote from the price service. > The flow on this page and > `submitBenchmarkQuoted` apply to a kind-2 market. A client of a kind-3 market requests the close > (`requestCloseFor`) and reads `SettlementPriced`. > > **On a feed-kind-4 market the venue's keepers settle too.** The price is read from an on-chain > oracle inside the settle, with the oracle accounts last; see > [on-chain oracle markets](/sdk/orders#on-chain-oracle-markets-feed-kind-4). A client requests the > close (`requestCloseFor` adds the market's terms account) and reads `SettlementPriced`. ## The close reasons | Reason | Code | Proved by | A stranger may submit it | Carries a quote | | - | - | - | - | - | | `voluntary` | 0 | the owner's request, then the window | yes, once the owner has requested it | yes | | `knockout` | 1 | the price | yes | yes | | `takeProfit` | 2 | the price | yes | yes | | `userExpiry` | 3 | the clock | yes | yes | | `tenorExpiry` | 4 | the clock | yes | yes | | `lastResort` | 5 | the clock, and no price being available | yes | **no** | | `borrowSpent` | 6 | the price, and the funding owed | yes | yes | No reason pays its submitter anything. `borrowSpent` closes a position whose funding has used up its payout. The trader receives 0, as for a knockout. It cannot occur while the funding rate is 0. ```ts theme={"dark"} import { CLOSE_REASON_BY_CODE, CLOSE_REASON_CODE, isPermissionless } from '@rekt-trading/1000x'; export const codeOf = CLOSE_REASON_CODE; // name -> on-chain discriminant export const nameOf = CLOSE_REASON_BY_CODE; // discriminant -> name export const permissionless = isPermissionless; // everything except an unrequested `voluntary` ``` `voluntary` is the one reason that needs the position owner's authority: the owner's signature, or a [session key](/sdk/sessions) the owner authorised. That authority signs only the request, which carries no quote, so a wallet can sign it and the Close button is one attempt. The settle that completes the request is sent by anyone with the window quote, and the venue's keepers do. ### The no-price close `lastResort` exists for a sustained oracle outage. It carries no quote and settles a live position at its own entry price, with the exit fee waived: the trader gets the stake back. A position already stamped as knocked out pays 0, and one stamped as having reached its rung is paid that level with the exit fee, as for a take-profit. It is legal only when all of these hold: * **either** the market is dark: if a market has had no posted price for 24 hours (the governed `dark_after_min`, read as `GovTable.darkAfterMin`), anyone can close any position on it, and the position gets its stake back. Anyone can post a signed price with `provePrice` to reset the clock. **Or** the position's own frozen tenor **plus** the grace in `config.lastResortGraceS` has elapsed since it opened, which only a position with a finite tenor can reach. A position with the indefinite tenor has only the dark arm. Earlier, it is refused `LastResortNotYetDue` (6192); * **no fresh price is available** for the market. With one available it is refused `LastResortPriceAvailable` (6193): settle at market with a priced reason instead; * the oracle is not frozen (`OracleFrozen`, 6190); * the position is not an unfilled order (`EntryNotFilled`, 6203) and no add waits for its price (`AddPending`, 6211). The `lastResort` transaction carries neither the ed25519 instruction nor the Instructions sysvar: it is `settle` with reason `5`. The program asks the dark arm only when the governance table is among the remaining accounts, so a refund that omits it can never fire on the indefinite tenor (`LastResortNotYetDue`). [Build it](#3-build-the-close) with the table, the market's fee-terms account and the pool's accounts. On a market with trading hours, a position that is not settled before its session's close ends at par. ### Settles can be stopped Two switches can stop closes on the venue. * **Settles disabled** (`config.settlesDisabled`): opens, adds, close requests, expiry marks, `settle` with **every** reason (`knockout` and `lastResort` included), `stamp_book`, `set_take_profit` and the return of an unfilled order or add (`void_open`, `reverse_add`) all refuse with `SettlesDisabled` (6191). Poll the flag rather than retrying on a timer, then send the same instruction once it reads false. * **Oracle frozen** (`config.oracleFrozen`): opens, adds, close requests, expiry marks, `stamp_book` and `lastResort` refuse with `OracleFrozen` (6190), as does the return of an order or add that needs a price. Every other `settle`, and `set_take_profit`, reads no price and fails `NoFreshPrice` (6007). Read the flag before you retry a `NoFreshPrice` that repeats. `settleGates` does not model either switch. Read both flags off the config before you send. ### The minimum hold `voluntary`, `takeProfit` and `userExpiry` require the position to have lived at least the governed minimum hold, in slots, since `openedSlot`: `resolveMinHoldSlots(config.minHoldSlots)`. Inside it they are refused `MinimumHoldNotMet` (6103). `knockout` and `lastResort` are never gated this way. `tenorExpiry` is gated only on a market with a session calendar. A market can add its own, longer hold (`market.closeHoldSlots`; 0 is none), and the larger of the two is in force. It gates a close request at the slot the request lands and a take-profit at the slot of the price that proves it, and returns `MarketHoldNotMet` (6236) when only the market's hold is not met. It never gates a mark or a knockout. The hold counts from the entry price, and after a filled add from the add's price. If your interface offers a close button the instant a position opens, it will revert. So will a keeper closing on a user timer just after an add, because a filled add re-stamps `openedSlot`. `settlePreview` takes no slot argument and does not model the hold: `closableFromSlotOf(position, config, market)` gives the first slot at which a close request can land. ## 1. Ask which reason applies Do not guess. `settlePreview` prices the six priced reasons at one price and one instant and names the one a keeper would submit. It does not model `lastResort`: decide that one from the clock and from whether you can obtain a price at all. A position that froze fee terms at open (`feeTermsSlot(position.flags) != 0`) is priced with the entry at that slot of its market's fee-terms account: the share of the gain the trader keeps, the fee rate at the exit move, and the fee base. Pass that account, decoded, as `feeTermsTable`. Without it, every close of such a position that pays a gain or a fee reads `FeeTermsTableRequired`, the refusal the program gives a settle that leaves the account out. A close at the barrier is priced either way. ```ts theme={"dark"} import { settlePreview, type ConfigView, type FeeTermsTableView, type PositionView, } from '@rekt-trading/1000x'; export function chooseReason( position: PositionView, config: ConfigView, exitPrice: bigint, nowUnix: bigint, submitter: string, owner: string, // decodeFeeTermsTable(bytes at feeTermsTablePda(market)), or null when the account does not exist. feeTermsTable: FeeTermsTableView | null, ) { const preview = settlePreview(position, config, exitPrice, nowUnix, submitter, owner, { feeTermsTable, }); // null when nothing is legal yet: that is a wait, not a failure. const reason = preview.suggested; const row = preview.reasons.find((r) => r.reason === reason) ?? null; return { preview, reason, payouts: row?.payouts ?? null, capped: row?.capped ?? false }; } ``` A knockout settles **at the barrier** however far past it the price ran, so it needs no exit price to be priced, and a slow submitter cannot make it worse. A close that is not a knockout pays in the order set out under [what a close pays](/sdk/positions#what-every-close-would-pay-right-now): a loss tax on a loss comes before the exit fee. ## 2. Check the gates the engine cannot see `settlePreview` models the reason's legality, because that is engine arithmetic. It does **not** model the refusals either side of the engine call: the market pin, the price, the entry exponent and the solvency guard. `settleGates` does. ```ts theme={"dark"} import { settleGates, type ConfigView, type GateReport, type MarketView, type Payouts, type PositionView, type QuoteView, type SettlePreview, } from '@rekt-trading/1000x'; /** * What LEAVES the vault when this position closes: the quantity the program's solvency guard * compares against the position's reserve. `poolDelta` stays inside the vault. `p.liquidator` reads * 0n on every settlement; keep it in the sum so this is the program's arithmetic, and never render * it as money a submitter receives. */ const totalOutflow = (p: Payouts): bigint => p.trader + p.liquidator + p.insurance + p.protocol; export function gatesForSettle(args: { config: ConfigView; market: MarketView; marketAddress: string; position: PositionView; quotes: QuoteView[]; preview: SettlePreview; reason: string; ownerIsSubmitter: boolean; }): GateReport { const row = args.preview.reasons.find((r) => r.reason === args.reason) ?? null; return settleGates({ config: args.config, market: args.market, // The market the SUBMITTER intends to use, passed deliberately so a caller that has two // markets confused is caught by the first gate rather than by the chain. marketAddress: args.marketAddress, position: args.position, quotes: args.quotes, outflow: row?.payouts ? totalOutflow(row.payouts) : null, // Always false: no settlement pays a submitter. liquidatorPaid: false, liquidatorTokenNamed: false, ownerIsSubmitter: args.ownerIsSubmitter, // Pass the reason. Omit it and you get no row for the one thing most likely to be wrong. reason: { name: args.reason, legal: row?.legal ?? false, why: row?.why ?? 'the engine names no such reason', }, }); } ``` > [!WARNING] > > **Always pass `reason`.** The type allows leaving it out, but without it the report can print `ok` > on every row for a transaction the chain will refuse. ## 3. Build the close ```ts theme={"dark"} import { PublicKey } from '@solana/web3.js'; import { CLOSE_REASON_CODE, assetId, configPda, ix, lastResortTableRemaining, marketPda, priceAccountsFor, toHex, traderPda, vaultPda, withCapitalRiders, withFeeTermsTable, type BuiltInstruction, type CloseReasonName, type ConfigView, type MarketView, type TraderAccountView, } from '@rekt-trading/1000x'; export function buildSettle(args: { /** The decoded config, read for this request. */ config: ConfigView; symbol: string; market: MarketView; submitter: PublicKey; owner: PublicKey; /** The owner's book, decoded: the payout destination is read from it. */ book: TraderAccountView; seq: bigint; reason: CloseReasonName; protocolToken: PublicKey; vaultToken: PublicKey; /** The session key's `TradeDelegate` PDA, or null when the OWNER is closing. */ delegate: PublicKey | null; }): BuiltInstruction { const built = ix.settle( { submitter: toHex(args.submitter), config: toHex(configPda().address), market: toHex(marketPda(assetId(args.symbol)).address), positions: toHex(traderPda(args.owner).address), vault: toHex(vaultPda().address), vault_token: toHex(args.vaultToken), // The book's recorded payout destination, and nothing else. Any other account is not paid: // the payout is held on the book instead. owner_token: args.book.payoutDestination, protocol_token: toHex(args.protocolToken), // Optional as a pair: both or neither. Pass neither. insurance: null, insurance_token: null, delegate: args.delegate ? toHex(args.delegate) : null, }, args.seq, // the handle, never the slot index CLOSE_REASON_CODE[args.reason], args.reason === 'lastResort' ? // No quote and no sysvar: the governance table (it is how the program asks the dark arm), // then the market's fee-terms account, which rides writable. withFeeTermsTable(lastResortTableRemaining(), args.market, args.config, 'last_resort') : // A priced reason carries the Instructions sysvar, the governance table, and the market's // fee-terms account when it has terms. Without the table the program refuses the settle // (`GovTableRequired`, 6221). priceAccountsFor(args.market, args.config, 'settle'), ); // The pool's accounts come last: `CapitalState` and the queue ring, both writable. return withCapitalRiders(built, 'settle', true); } ``` > [!NOTE] > > **`owner_token` is required and it is the only account a settlement pays.** It must be the book's > recorded `payoutDestination`; a settle naming any other account escrows the payout on the book > rather than paying it, and so does one whose destination has been closed or frozen. The trader > then claims it with `claimPayout`; see [reading positions](/sdk/positions#a-payout-that-has-not-been-collected). > **`WrongPayoutDestination` (6150) is reserved and raised by nothing. Do not branch on it.** ### Send it with its quote A priced settle carries its quote: the quote's ed25519 instruction immediately before `settle`, the compute-budget pair after. `submitBenchmarkQuoted` takes the quote as it arrives (its assembled ed25519 instruction data and the ed25519 program id) and what the signed payload decodes to (`quote`). It evaluates the protocol gates you hand it **first**, then composes, signs, measures the bytes, checks the distinct-signer count against `market.minSignatures`, and simulates. Every check is a `Gate`, so a failure still prints a table that explains itself. To obtain the quote, see [Getting prices](/sdk/prices). ```ts theme={"dark"} import { Connection, Keypair, PublicKey } from '@solana/web3.js'; import { SenderRefusal, computeUnitLimit, submitBenchmarkQuoted, type BuiltInstruction, type GateReport, type MarketView, type PostedQuote, type SubmitOutcome, } from '@rekt-trading/1000x'; /** A signed quote for one market, as the send needs it. */ export interface SignedQuote { /** The quote's assembled ed25519 instruction data, hex, exactly as it arrived. */ ed25519InstructionDataHex: string; /** The ed25519 program id the quote names. */ ed25519ProgramId: PublicKey; /** What the signed payload decodes to: price, publish slot, distinct signers. */ quote: PostedQuote; } export async function sendSettle(args: { connection: Connection; payer: Keypair; built: BuiltInstruction; signed: SignedQuote; market: MarketView; protocolGates: GateReport; priorityFeeMicroLamports: number; /** Leave true until you have watched this path work. It sends nothing. */ dryRun: boolean; }): Promise { try { const out = await submitBenchmarkQuoted({ connection: args.connection, commitment: 'confirmed', ed25519InstructionDataHex: args.signed.ed25519InstructionDataHex, ed25519ProgramId: args.signed.ed25519ProgramId, quote: args.signed.quote, built: args.built, payer: args.payer, signers: [args.payer], priorityFeeMicroLamports: args.priorityFeeMicroLamports, protocolGates: args.protocolGates, minSignatures: args.market.minSignatures, dryRun: args.dryRun, }); console.log( `${args.built.name}: ${out.bytes} bytes, ${out.simulatedCu} CU of ${computeUnitLimit(args.built.name)} declared`, ); // Read `confirmation` before `revert`: a send the cluster never confirmed (`expired`, // `unconfirmed`) also carries `revert: null`. Read the chain before you send it again. if (out.signature === null) console.log('dry run: nothing was sent'); else if (out.confirmation !== 'confirmed') console.log(`sent ${out.signature}, ${out.confirmation}`); else if (out.revert !== null) console.log(`reverted ${out.signature}: ${JSON.stringify(out.revert)}`); else console.log(`landed ${out.signature}`); return out; } catch (e) { // A refusal before signing: a failed gate, a short quote, or a packet that does not fit. if (e instanceof SenderRefusal) console.error(`refused before signing: ${e.message}`); throw e; } } ``` > [!NOTE] > > **`dryRun: true` is the posture to default to.** It builds and signs exactly what would be sent, > measures the real byte count, simulates with signature verification on, and stops. It is safe > against mainnet. A `lastResort` settle has no quote to carry: compose `settle` and the > compute-budget pair, and simulate before you send. ### Request or mark, then settle Three reasons are two steps. | Reason | Step 1, which carries no quote | Who sends step 1 | Step 2 | | - | - | - | - | | `voluntary` | `request_close` (`ix.requestClose`) | the owner or a session key | `settle`, sent by anyone | | `userExpiry` | `mark_expiry` with reason 3 (`ix.markExpiry`) | anyone, from the deadline | `settle`, sent by anyone | | `tenorExpiry` | `mark_expiry` with reason 4 | anyone, from the deadline | `settle`, sent by anyone | Step 1 writes the **exit target**, `d` slots after it lands (`CloseRequested.exitTarget`, `ExpiryMarked.exitTarget`). Step 2 is the `settle` above with the recorded reason and the **window quote**: the first price of the venue's price feed at or after `exitTarget + K × W`, where `K` is the count of whole windows of `W` slots since the target. Only that quote prices it, so a settler chooses nothing. A settle before the target returns `ExitQuoteNotYetDue` (6216), another quote `NotWindowQuote` (6217), another reason `ExitReasonMismatch` (6215), and an expiry with no mark `ExitNotAnchored` (6214). A request cannot be withdrawn, and a second one returns `ExitPending` (6213): treat it as success. `knockout` and `takeProfit` stay one step. Their price can be up to `W_ko` slots old, and after a request or a mark only a price that is not later than the exit price proves a level. [Orders and closes](/sdk/orders) has the timing settings and the whole contract. ### The pool's accounts A settle needs `CapitalState` and the queue account, both writable, as trailing remaining accounts found by address; without them it is refused. The same accounts ride on a few other instructions: | Instruction | Capital accounts it needs | | - | - | | `settle`, every reason | `CapitalState` and the queue account, both writable | | `void_open`, `reverse_add`, `set_take_profit` | `CapitalState` (writable) | | `pay_queue`, anyone | the config (read), `CapitalState`, the queue account, the vault and its token account (all writable), then pairs of an account's book and its destination | | `open` and `add_collateral` | **none** | `withCapitalRiders(built, kind, true)` appends them, in the order the program reads them, after every other remaining account. No lookup table carries them: they ride as static keys, 32 bytes each, so measure the signed transaction. `SettlementPriced.trader` is the amount **paid now**. When part of a win was queued, `SettlementQueued` carries the amount owed, the amount paid now and the amount queued, with the line range the queued part occupies; `QueuePaid` carries each delivery with the same range, so every delivered unit joins exactly one settle. ## 4. Check the money afterwards The settlement's legs must add up. `isConserving` compares the pool delta with the legs, so a fee miscounted or a rounding remainder dropped makes the two sides disagree. ```ts theme={"dark"} import { isConserving, type Payouts, type PositionView } from '@rekt-trading/1000x'; export function assertConserved(payouts: Payouts, position: PositionView): void { // poolDelta === collateral - (every leg that leaves the vault) if (!isConserving(payouts, position.collateral)) { throw new Error('the settlement legs do not conserve: do not send another trade until this is explained'); } } ``` The inflow is the position's collateral. The **entry** fee is not part of it: it is taken at open, from inside the budget, and never reaches settlement. `SettlementPriced.trader` is what was paid now. A win that was partly queued is **owed** in full: add the queued amount from `SettlementQueued` to the trader leg before you compare the legs with the position's collateral. The SDK does it: `readTradeHistory` and `closedTradesInTransaction` pair the `SettlementQueued` of the same transaction, verify the settlement over the owed legs, and expose the split on each `ClosedTrade` as `paidNow` and `queued`. > [!NOTE] > > **The SDK's settlement mirror includes [funding](/how-it-works#funding).** `settlePreview`, > `settle`'s breakdown and `reconstructTrade` charge it from the position's frozen rate > (`borrowRateBpsPerHour`), after the exit fee. The funding rate is 0, so nothing is charged. ## 5. Confirm, then read what the close paid from its own transaction `confirmSignature` waits for a signature and returns the chain's verdict with the landed transaction. `closedTradesInTransaction` reads the settlement out of that transaction; it is the same function `readTradeHistory` files each closed trade with, so a close's receipt and its history row agree field for field. ```ts theme={"dark"} import { Connection, PublicKey } from '@solana/web3.js'; import { closedTradesInTransaction, confirmSignature, connectionSignatureReader, receiptOf, type ConfigView, } from '@rekt-trading/1000x'; export async function closeResult( conn: Connection, signature: string, lastValidBlockHeight: number, owner: PublicKey, mint: PublicKey, config: ConfigView, seq: bigint, ) { const out = await confirmSignature(connectionSignatureReader(conn), signature, lastValidBlockHeight, { waitMs: 12_000, }); // `unconfirmed` may still land: look the signature up again before you send anything else. if (out.confirmation !== 'confirmed') return { verdict: out.confirmation } as const; if (out.err !== null) return { verdict: 'reverted', err: out.err } as const; if (out.landed === null) return { verdict: 'landed' } as const; const receipt = receiptOf(out.landed, { tokenOwners: [owner.toBase58()], mint: mint.toBase58() }); // Match the seq: one transaction can settle several of the owner's positions (a keeper batch). const trade = closedTradesInTransaction(out.landed, owner, config).find((t) => t.seq === seq) ?? null; // `receipt.ownerDelta` is what reached the owner's token accounts in this transaction. return { verdict: 'landed', trade, paidToOwner: receipt.ownerDelta, complete: receipt.complete } as const; } ``` `confirmSignature` polls `getSignatureStatuses` every `pollMs`. A long-lived process (a keeper, a server) can pass `push: connectionSignaturePush(conn)`: a `signatureSubscribe` at `confirmed` wakes the poll when the cluster confirms. The poll still reads the status before it returns, so a silent or wrong channel costs latency and never a wrong answer. It is off by default. Do not use it inside a serverless function. The rules this follows: * Only `confirmed` or `finalized` with `err === null` is a success. A `processed` status is not. * A receipt with `complete: false` came from a missing or truncated log. Print no figure from it. * A payout is in the owner's wallet only when `ownerDelta` shows it. A settle whose destination cannot receive escrows the payout instead, and the transaction then carries `PayoutEscrowed`. A position a keeper settled is found the same way, from the newest transactions on the book: ```ts theme={"dark"} import { connectionReader, readSettlementForSeq } from '@rekt-trading/1000x'; // `minContextSlot`: the slot of the read that showed the position gone. const [trade] = await readSettlementForSeq(connectionReader(conn), owner, [seq], config, { minContextSlot }); ``` A seq it does not find is absent from the result; `readTradeHistory` is the full scan. Both reads fetch one transaction per signature, and a landed transaction never changes. If you look more than once (a poll for a close, or the history list beside a receipt), wrap the reader once: ```ts theme={"dark"} import { connectionReader, memoReader, readTradeHistory } from '@rekt-trading/1000x'; const reader = memoReader(connectionReader(conn)); // keep it for the life of the process const first = await readTradeHistory(reader, owner, config); // 1 list + one read per transaction const again = await readTradeHistory(reader, owner, config); // 1 list call when nothing is new ``` `memoReader` keeps only a transaction the node returned. A `null` or a thrown read is asked again, and a `before` page or a `minContextSlot` look goes straight to the node. A transaction that `@solana/web3.js` cannot parse is read by one raw call, so an unrelated transaction that names a trader's account does not stop the scan. ## Anyone can settle Every close ends with a `settle` that anyone may send, and nobody is paid for sending one. The venue's keepers send settles and stamps. Send one yourself only to close your own position faster than they do. The builders on this page and `submitBenchmarkQuoted` are all you need: build `settle` with the reason the position's phase names, attach the window quote, simulate, send. A refusal you meet on the way is on [error handling](/sdk/errors). # Report a security issue Source: https://docs.rekt.money/security How to report a vulnerability in Knockout or Minute, what to send, what we ask of you, and how rewards work. **If you find a security issue, tell us before you tell anyone else.** Send it to **[support@asymmetra.xyz](mailto:support@asymmetra.xyz)** with the subject line `Security report`. Reports of any kind are welcome. Good-faith research is welcome. ## What to send * What the issue is, and what an attacker could do with it. * Where it is: the program and instruction, the SDK function, the page or the endpoint. * The steps to reproduce it. A run on a local validator or a mainnet fork is the best proof. * Your contact, and the name to credit if you want credit. ## What we ask * Report privately, and give us reasonable time to fix the issue before you publish. * Prove the issue with the least harm. Use your own funds and the smallest stake. Do not take or move funds that are not yours. * Do not run a denial-of-service or spam test against the live programs, the price service or the apps. * Do not use social engineering against our team, our users or our providers. * Do not read, change or keep other people's data. ## What we do * We tell you what we found and what we will do about it. * We credit you when the fix is public, if you want that. ## Rewards **Rewards are at our discretion, and they depend on how critical the finding is.** The findings we care about most are the ones that put trader funds or pool funds at risk, or that let someone stop trading or settlement. A finding of that kind is the kind that earns a reward. Lower-severity findings are still welcome, and we fix them. They do not usually earn a reward. That includes ordinary website issues, SDK bugs that put no funds at risk, and best-practice suggestions. There is no fixed table of amounts. ## Scope | In scope | Where | | - | - | | The Knockout program | `1oooxLtzLiYV6LcDybrEPcyXVLPWGnAmeif9s5oNrp6` on Solana mainnet | | The Minute program | `MinXAXaPZezFMc8mm1uZnK8NcYt7Fhbr7Eifdnw7cfH` on Solana mainnet | | The public data API | `data.rekt.trading` | | The apps | Anywhere they build or send a transaction for these programs | Not in scope: * Services we do not run: wallets, RPC providers, exchanges and the Solana network. * Anything that needs the victim's own device or key to be compromised first. * Limits that are already stated on the [risk](/risk) page. > [!NOTE] > > Knockout and Minute are early alpha software and have not been audited by a third party. Read the > [risk](/risk) page before you trade. # Wheelman Source: https://docs.rekt.money/tools/wheelman A trading bot, a command line and a local MCP server for Knockout and Minute. You run it with your own wallet and your own RPC endpoint. Wheelman is an open-source bot, command line and local MCP server for Knockout and Minute. It runs on your machine, with your wallet and your RPC endpoint. It is built on the SDK, [`@rekt-trading/1000x`](/sdk/installation). Source and full reference: [the Wheelman repository](https://github.com/Asymmetra/rekt-wheelman). License: Apache-2.0. ## What it does | command | what it does | | - | - | | `markets` | every market: open or not, stake bounds, leverage, fees | | `preview ` | the stake, the barrier, and the payout at the target and at the barrier, after every fee | | `open ` | one Knockout position (`--target`, `--timer`), or a Minute round (`--minute`) | | `close ` | a close request; the venue's keepers complete it | | `positions` | open positions, live rounds, balances, today's result | | `run [strategy]` | the bot, with one strategy | | `session start\|status\|end` | a session key for an agent | | `mcp` | a stdio MCP server with the same commands as tools | `--referrer ` on `open` and `session start` links your wallet to a referrer in the same transaction, when your wallet has no link yet. Your own key signs it; a session key cannot. See [Referrals](/referrals). Every command takes `-o json` and prints one line: `{"ok": true, "data"}` or `{"ok": false, "error": {"category", "code", "message", "retryable"}}`. See [Error handling](/sdk/errors). The bot comes with five strategies (`knockout-momentum`, `knockout-fade`, `knockout-straddle`, `minute-trend`, `minute-schedule`) and a template for your own. Every parameter has a default and a bound. The defaults are starting points, not recommendations. ## Your wallet, your keys * Wheelman holds no funds and hosts nothing. Your wallet signs, or a session key you authorise does. * **Agents trade with a session key, never with your wallet.** `wheelman session start --allowance 20 --expires 24h` authorises a new key to spend at most the allowance, in USDC, until the expiry. The program enforces both. `wheelman session end` revokes it. See [Session keys](/sdk/sessions). * **Risk limits apply before every open**, from the bot, the command line or an agent: the largest stake, the most open positions, a daily loss stop and a minimum balance. Wheelman does not trade without a daily loss stop. A close is never blocked. * `--paper` simulates fills and sends nothing. `--dry-run` builds and simulates the real transaction on mainnet and sends nothing. A paper result does not say what live trading pays. * `PRICE_SOURCE=replay` with `REPLAY_FILE` runs the bot in paper mode on a tape of recorded prices, one JSON line a price: `{"time": 1767225600000, "market": "BTC", "price": 100000}`. ## Install Wheelman needs Node 22.18 or later. The SDK alone needs Node 20.19 or later, or Node 22.12 or later. ```sh theme={"dark"} npm install -g @rekt-trading/wheelman wheelman setup wheelman markets wheelman open BTC long 1 --paper ``` To run from source instead, clone [the repository](https://github.com/Asymmetra/rekt-wheelman) and run `npm install && npm link` in it. ## Use it from an agent The MCP server serves `markets`, `preview`, `positions` and `session_status`. With a session key it adds `open` and `close`, signed by the session key. With `--paper` it adds them as paper-only. It never signs with the owner's key. ```sh theme={"dark"} claude mcp add wheelman -- node /path/to/wheelman/src/cli.ts mcp --env /path/to/agent.env ``` `agent.env` holds `RPC_URL`, `OWNER`, `SESSION_KEYPAIR_PATH` and the risk limits, and no owner key. The repository also has a skill file for agents, `skills/wheelman/SKILL.md`, and the setup for Codex and Cursor: [README](https://github.com/Asymmetra/rekt-wheelman#agents). # Alerts Source: https://docs.rekt.money/using-rekt/alerts Browser notifications from Rekt: how to turn them on and what each group sends. Rekt can send notifications to your browser, even with the tab closed. Turn them off any time. ## Turning them on * Open **Settings** and turn on alerts in this browser. Your browser asks for permission once. * Alerts are per browser. Turn them on in each browser you use. * Logging out stops alerts on that browser. * Some browsers cannot show them, such as Safari on an iPhone and the browsers inside other apps. There the setting does not appear. ## What each group sends Settings has four groups. Each one is on or off for your whole account. | Group | What it sends | | - | - | | Trade alerts | Money at risk on an open position | | Results & wins | Minute round results | | Rewards & invites | Someone joined with your link, an invite's first trade, a weekly total of your invite points, and a reminder before your daily streak ends | | News & tips | Tips while you are getting started | Announcements from Rekt always come through. They are not in a group. ## When they arrive * Most alerts come only when you are not using Rekt. Money at risk always comes. * Knockout results show in the app. They are not sent as notifications. * You never get an alert for your own trade going through. # Challenges Source: https://docs.rekt.money/using-rekt/challenges One-time goals that each pay points once you finish them. Challenges are one-time goals. Finish one and its points land on their own. There is nothing to claim. Each challenge pays once. ## The challenges | Challenge | Done when | | - | - | | Open your first Knockout | You open a Knockout trade that gets points | | Play a Minute round | You play one Minute round | | Go 1000× | You open a Knockout or a Minute round at 1000× | | Place 5 trades | You place 5 trades that get points | | Place 10 trades | You place 10 trades that get points | | Invite someone | Someone you invite makes their first trade | | Follow traders | You follow the number of traders the challenge names | | Turn on alerts | You turn on alerts in your browser | | Add your email | You verify your email with a code and keep the newsletter on | | Complete your profile | You add a bio and pick your country | The app shows each challenge's reward, and only the challenges open to you right now. ## Good to know * **A trade that gets points** is a Knockout trade with a stake of \$1 or more, or any Minute round. * **Invite someone** is a one-time bonus on your first completed invite. It comes on top of the 250 points you and your invite each get over their first 3 trades, never instead of it. * **Place 5 and Place 10 trades** count only trades placed after those goals launched. * **A finished challenge** keeps the reward it paid, even if the reward changes later. * **Your rank** does not multiply challenge points. # Daily streak Source: https://docs.rekt.money/using-rekt/daily-streak Trade any day to keep your streak. Every day in a row pays more, and every 5th day pays a bonus. Make a trade any day to keep your streak. Every day in a row pays more, and every 5th day pays a bonus. Miss a day and it starts over. ## What counts Your first trade of the day that gets points: a Knockout trade with a stake of \$1 or more, or any Minute round. More trades that day keep the same streak day. They do not add another one. ## When a day starts Days change at 00:00 UTC. The app shows that time in your own time zone, for example 5:00 PM. ## What it pays * **Every day in a row.** Day 1 pays 5 points, day 2 pays 10, and each day adds 5 more, up to 50 a day from day 10. * **Every 5th day.** A bonus on top. It grows with your rank. These are today's figures. The Streak sheet shows what your next day and your next bonus pay. Streak points land on their own and your rank does not multiply them. ## Missing a day Miss a day and your streak starts over at day 1. There is no grace day. If you have a streak of 2 days or more and have not traded today, the app counts down to the end of the day. With alerts on, you get a reminder before it ends. See [Alerts](/using-rekt/alerts). # Invites Source: https://docs.rekt.money/using-rekt/invites Invites get you two things, kept apart: USDC from your invites' trades, and points. Share your invite link. When someone joins with it, you get two separate things: * **USDC**, from their Knockout and Minute trades. * **Points**, over their first 3 trades and then a share of their trading points. Your link is `app.rekt.money/ref/` followed by your username. Open **Invite people** in the app to copy or share it. ## USDC * Every Knockout and Minute trade your invites make sends you USDC, at your rate, for as long as they trade. * Your rate starts at 20% and rises as your invites trade more, up to 50%. * You claim your USDC in the web app, from **Invite people**, once you have \$1 or more to claim. * The Invite sheet shows what came to you so far, what you claimed and what is waiting. Your rate, by your invites' trading fees, today: | Your invites' trading fees | Your rate | | - | - | | From the start | 20% | | \$10,000 | 25% | | \$40,000 | 30% | | \$150,000 | 35% | | \$500,000 | 40% | | \$650,000 | 45% | | \$1,000,000 | 50% | Some partner codes raise the rate for a set time. The app shows your rate as it is now, and any raise with its end date. ## Points * You and your invite each get 250 points over their first 3 trades: 150 on the first, then 50 on each of the next two. * Your first invite to complete also gets you the **Invite someone** challenge: a one-time bonus on top of that 250, paid once. The app shows its figure while the challenge is open to you. * After that, you get a share of the points they get from trading, for as long as they trade. * Your share rises with your rank: 10% at Bronze, 20% at Silver and Gold, 30% at Platinum and Diamond, 40% at Hope and Pink Star. * A trade counts when it gets points: a Knockout trade with a stake of \$1 or more, or any Minute round. These figures are today's. The app always shows the current ones. ## What your invite gets * **250 points** over their first 3 trades. * **10% off cash-out fees**, on every cash-out, for good. An invite linked to you before 2026-11-10 keeps 25% off. ## Good to know * Each account has one inviter. Add a code when you sign up, or within 7 days from the Points sheet. * You cannot use your own code. * Public pages show totals only, never who invited whom. # Points and ranks Source: https://docs.rekt.money/using-rekt/points-and-ranks How you get points on Rekt, how your rank follows from them, and what each rank changes. Trade, play Minute, invite people and keep a streak to get points. Your total points set your rank. Higher ranks raise your stake limits and your share of your invites' points. ## Getting points | Where | What you get today | | - | - | | Knockout | 5 points per \$1 of your stake | | Minute | 5 points per \$1 of your opening stake | | Invites | Bonus points over each invite's first 3 trades, then a share of their trading points. See [Invites](/using-rekt/invites). | | Daily streak | Points for every day in a row you trade. See [Daily streak](/using-rekt/daily-streak). | | Challenges | A one-time reward for each goal you finish. See [Challenges](/using-rekt/challenges). | * A trade counts when it gets points: a Knockout trade with a stake of \$1 or more, or any Minute round. * A Minute double-down gets no points. One round gets points once. * Points land on their own. There is nothing to claim. The rates above are today's. The app always shows the current ones. ## Your rank boosts your trading points Your rank multiplies the points you get from Knockout and Minute. It does not multiply invite, streak or challenge points. The higher your rank, the bigger the boost. ## The ranks Your rank comes from your total points. | Rank | Points | | - | - | | Bronze | 0 | | Silver | 1,000 | | Gold | 5,000 | | Platinum | 15,000 | | Diamond | 50,000 | | Hope | 100,000 | | Pink Star | 500,000 | | Classified | Sealed until someone reaches it | ## What a rank changes * **Stake limits.** Each rank has its own highest Minute stake and Knockout stake. Your limit is the lowest of three: your rank's cap, the game's cap and what the pool supports. The pool's limit can sit below your rank's cap, and it moves with the pool. * **Your share of your invites' points.** It rises with your rank. See [Invites](/using-rekt/invites). * **Your streak bonus.** Every 5th streak day pays a bonus that grows with your rank. * **Price-dot icons.** Gold, Platinum and Hope unlock price-dot icons for your charts. Open **Your rank** in the app and tap **Compare all ranks** to see every rank's limits and perks as they are today. ## The leaderboard The leaderboard is open to Silver and above. # The venue Source: https://docs.rekt.money/venue What the Knockout program does: admission and the queue, the pricing path, the limits on loss and payout, settlement, size and fees, and where each one is read on chain. Everything on this page is a rule or a value of the program on Solana mainnet. It is early, unaudited software: read [Risk](/risk) before you trade. ## Three bounds, fixed at open * **Loss is bounded.** The most you can lose is your stake. There is no margin call, no negative balance and no clawback. * **Payout is bounded.** A target cannot exceed a multiple of the stake, `config.params.payoutCapMultiple`. How a win is paid is under [admission and the queue](#admission-and-the-queue). * **Time is fixed at open.** The tenor is read from `config.params.tMaxSeconds` and frozen onto the position. It is the indefinite value, so a position has no protocol clock: it ends at its barrier, its target, a close, its own timer, or the no-price close. The funding rate is 0, and a position keeps the rate it opened with. ## Admission and the queue Opening a position takes your stake and nothing else. The program decides whether the position fits when the venue fills the order, against a rule it applies per market and in total. An order that does not fit is returned: your whole stake comes back and no fee is charged. A hedge, a smaller target and a close are never refused by this rule. At a close, your stake comes back at once and the profit is paid from the pool's free cash. **A win is paid in full. Part of it may be paid later, in order. There is no guaranteed time. The amount queued ahead of you is shown.** What the pool cannot pay yet joins a queue, first in, first out, and it is funded by cash that other positions leave in the pool. Anyone may send the instruction that delivers funded queue money (`pay_queue`); it goes to the wallet recorded on the account. When the line is nearly full, a second unpaid win of the same account waits behind its first. The settlement events say how much was paid now and how much was queued. The program has no auto-deleveraging, no socialised loss and no write-down of an amount owed: it is paid in full or stays owed. A payout that cannot be delivered is held for its trader, and it is released to the pool if nobody claims it within `config.params.unclaimedPayoutExpiryS`. The program has no instruction to deposit into the pool or to redeem from it; see [the liquidity pool](/liquidity). ## The pricing path Your entry is the first price of the venue's price feed at or after your order's target slot, a short delay after the order lands. It is a signed quote, and the program verifies it when the filler writes it. The function that prices an order takes the market and the quote and never the stake, so every size fills at the same price. An order is returned when its price does not clear one of these: * **Time.** It comes within a governed number of slots after the target, and a filler writes it inside the fill window. * **Signatures.** At least `market.minSignatures` distinct keys that the program recognises. * **Quality.** It meets the venue's quality rule for an entry. See [orders and closes](/sdk/orders) for the rules and [Risk](/risk) for what they do not cover. ## The barrier At 1000x the barrier sits a very small distance from the entry. A move too small to see on a chart can knock the position out. Barrier and take profit are both distances from the entry, so the 1000x sets how fast a position ends. ## Settlement Settlement is permissionless for every outcome that has evidence behind it: the barrier touched, the target reached, the position's own timer run out, and a finite protocol tenor expired. Any address may send that transaction, and the money goes to the owner's account whoever sent it. Every priced close carries a signed quote from the venue's price feed. If no quote can be obtained for a long time, a no-price close (`lastResort`) applies: it pays a live position its stake back with the exit fee waived, and a position already stamped at a level is paid that level (a target level pays the exit fee). It is refused while the oracle is frozen. On a market with trading hours, a position that is not settled before its session's close ends at par. A voluntary close needs the owner's authority: a signature, or a session key the owner authorised. The settle that completes it can be sent by anybody, at the first price after a short delay from the request. > [!WARNING] > > **Two switches can stop closes, and neither can be lifted by the key that sets it.** The guardian can > freeze the oracle, which refuses opens and leaves every priced close without a price. It can also > disable settles, which refuses every close. Only the config authority lifts either. Read > `config.oracleFrozen` and `config.settlesDisabled`. ## What you sign on an open You sign a total budget, and the venue takes its fee from inside it, so the debit is at most that number. You also sign `min_collateral_out`, the smallest position you accept for that budget. The position the budget buys is computed from the live parameters in the slot where the transaction executes. If a governance change in between would buy a smaller position, the transaction refuses. A `min_collateral_out` of zero is refused (`MinCollateralOutRequired`). The terms are fixed when the order lands. The entry is not: it is set by the next price. The barrier and the target are distances from that entry, so their prices exist once the order is filled. Every number below is computed from the live parameters for the exact terms you are about to open: ```ts theme={"dark"} import { openPreview, type ConfigView, type MarketView } from '@rekt-trading/1000x'; export function quote(config: ConfigView, market: MarketView, nowUnix: bigint) { // The fourth argument is the optional target in basis points of stake: 20_000 is 2.00x, the floor. const preview = openPreview(config, market, 1_000_000n, 20_000, nowUnix); return { // What you transfer, and what the fee inside it is. totalDebit: preview.totalDebit, entryFee: preview.entryFee, // The gross payout at the target, before the exit fee and the share of the gain the terms withhold. maxPayout: preview.maxPayout, // What the trader receives at the barrier. barrierPayout: preview.barrierPayout, }; } ``` An interface shows `barrierPayout` on the same screen as the open button. ## Size, cap and stake BTC, ETH, SOL, XRP and HYPE are listed at a tier of **1000x**. The protocol's payout cap is `config.params.payoutCapMultiple`. See [markets](/markets). * **The 1000x decides the distance** the price has to move, in either direction, before the position ends. It sets the time scale of the position. * **The payout cap decides the ceiling.** A target above it is refused, and a position with no target of its own has the cap as its target. Every market is 1000x. The market's tier (`market.tier`) is a ceiling and the venue's `config.minTier` is a floor, so every position opens at 1000x. A request above the ceiling or below the floor is refused. Stakes run between `minCollateral` and `maxCollateral`. Each of these is a governed field: read it from the chain. [Fees and limits](/limits) has the values, with the date they were read. ## Fees There is an entry fee (read `config.params.entryFeeBps`; it is 0, so an open is free), a loss tax on a close at a loss, an exit fee on most closes (not on one paid at the barrier, nor on a no-price close that returns the stake of a live position), and funding, which is a governed rate (`borrowRateBpsPerHour`) that is 0. The loss tax is a share of the loss, taken before the exit fee ([how a loss is calculated](/limits#how-a-loss-is-calculated)). The exit fee is a share of the exit value: a lower rate on a win and a higher rate on a loss. On a gain the terms also withhold part of the gain: the share you keep rises with the size of the move, so a target pays less than its multiple. [Fees and limits](/limits#how-a-win-is-calculated) has the values, dated, and a worked example. Every rate is written on chain, and the ones that apply to a position are frozen onto it at open. A returned order or add returns the whole stake. [How it works](/how-it-works#the-fees) has each fee, where it is read from and where it goes, and [Fees and limits](/limits) has the rates. A wallet linked to a referrer pays a lower exit fee, and the referrer is credited a share of the protocol's part of that wallet's trades. [Referrals](/referrals) has the rules. ## What the product does not do * **It is not a hedge.** A knockout ends the position at the moment a hedge would be needed. * **It does not fill at the price on your screen.** Entry and exit are the venue's next prices after a short delay. A close you ask for cannot be withdrawn, and its price is not locked until it settles. * **It does not roll over.** A position ends by its own rules. * **Adding to a position does not defend it.** Adding while ahead moves the barrier toward the price. See [adding to a position](/how-it-works#adding-to-a-position). ## Read it on chain | Item | Where it lives on chain | | - | - | | What the stakes hold | `vault.totalReserved` and the position's `collateral` on its book | | The queue: what is owed and what is funded | the pool's capital and queue accounts (`capitalPda()`, `queuePda()`); the `SettlementQueued` and `QueuePaid` events | | The entry price | the `EntryFilled` event, and the position's `entryPrice` once the order is filled | | The maximum loss | the position's `collateral` | | The 1000x tier and payout ceiling | `market.tier` and `config.params.payoutCapMultiple` | | The funding rate | `config.params.borrowRateBpsPerHour` | | Whether closes can be stopped | `config.oracleFrozen` and `config.settlesDisabled` | | Everything a trade must clear | [the gate list](/sdk/gates), each with the error it raises | ``` solana account --url "$SOLANA_RPC_URL" # every fee, bound and cap in force solana account --url "$SOLANA_RPC_URL" # pool assets, the stakes held solana program show --url "$SOLANA_RPC_URL" # who can upgrade the program ``` The SDK exports `PROGRAM_ID`, and `configPda()` and `vaultPda()` derive the two addresses. The SDK decodes the accounts and events, and the package carries the program's IDL. For integration questions, write to [support@asymmetra.xyz](mailto:support@asymmetra.xyz).