@percolatorct/sdk 1.0.0-beta.12 → 1.0.0-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,347 +0,0 @@
1
- import { Connection, type Commitment, type ConnectionConfig } from "@solana/web3.js";
2
- /**
3
- * Configuration for exponential-backoff retry on RPC calls.
4
- *
5
- * @example
6
- * ```ts
7
- * const retryConfig: RetryConfig = {
8
- * maxRetries: 3,
9
- * baseDelayMs: 500,
10
- * maxDelayMs: 10_000,
11
- * retryableStatusCodes: [429, 502, 503],
12
- * };
13
- * ```
14
- */
15
- export interface RetryConfig {
16
- /**
17
- * Maximum number of retry attempts after the initial request fails.
18
- * @default 3
19
- */
20
- maxRetries?: number;
21
- /**
22
- * Base delay in ms for exponential backoff.
23
- * Delay for attempt N is: `min(baseDelayMs * 2^N, maxDelayMs) + jitter`.
24
- * @default 500
25
- */
26
- baseDelayMs?: number;
27
- /**
28
- * Maximum delay in ms (backoff cap).
29
- * @default 10_000
30
- */
31
- maxDelayMs?: number;
32
- /**
33
- * Jitter factor (0–1). Applied as random `[0, jitterFactor * delay]` addition.
34
- * @default 0.25
35
- */
36
- jitterFactor?: number;
37
- /**
38
- * HTTP status codes considered retryable.
39
- * Errors matching these codes (or containing their string representation)
40
- * will be retried.
41
- * @default [429, 502, 503, 504]
42
- */
43
- retryableStatusCodes?: number[];
44
- }
45
- /**
46
- * Configuration for a single RPC endpoint in the pool.
47
- *
48
- * @example
49
- * ```ts
50
- * const endpoint: RpcEndpointConfig = {
51
- * url: "https://mainnet.helius-rpc.com/?api-key=YOUR_KEY",
52
- * weight: 10,
53
- * label: "helius-primary",
54
- * };
55
- * ```
56
- */
57
- export interface RpcEndpointConfig {
58
- /** RPC endpoint URL. */
59
- url: string;
60
- /**
61
- * Relative weight for round-robin selection.
62
- * Higher weight = more requests routed here.
63
- * @default 1
64
- */
65
- weight?: number;
66
- /**
67
- * Human-readable label for logging / diagnostics.
68
- * @default url hostname
69
- */
70
- label?: string;
71
- /**
72
- * Extra `ConnectionConfig` options (commitment, confirmTransactionInitialTimeout, etc.)
73
- * merged into the Solana `Connection` constructor for this endpoint.
74
- */
75
- connectionConfig?: ConnectionConfig;
76
- }
77
- /**
78
- * Strategy for selecting the next RPC endpoint from the pool.
79
- *
80
- * - `"round-robin"` — weighted round-robin across healthy endpoints.
81
- * - `"failover"` — use the first healthy endpoint; only advance on failure.
82
- */
83
- export type SelectionStrategy = "round-robin" | "failover";
84
- /**
85
- * Full configuration for the RPC connection pool.
86
- *
87
- * @example
88
- * ```ts
89
- * import { RpcPool } from "@percolator/sdk";
90
- *
91
- * const pool = new RpcPool({
92
- * endpoints: [
93
- * { url: "https://mainnet.helius-rpc.com/?api-key=KEY", weight: 10, label: "helius" },
94
- * { url: "https://api.mainnet-beta.solana.com", weight: 1, label: "public" },
95
- * ],
96
- * strategy: "failover",
97
- * retry: { maxRetries: 3, baseDelayMs: 500 },
98
- * requestTimeoutMs: 30_000,
99
- * });
100
- *
101
- * // Use like a Connection — same surface
102
- * const slot = await pool.call(conn => conn.getSlot());
103
- * ```
104
- */
105
- export interface RpcPoolConfig {
106
- /**
107
- * One or more RPC endpoints. At least one is required.
108
- * If a bare `string[]` is passed, each string is treated as `{ url: string }`.
109
- */
110
- endpoints: (RpcEndpointConfig | string)[];
111
- /**
112
- * How to pick the next endpoint.
113
- * @default "failover"
114
- */
115
- strategy?: SelectionStrategy;
116
- /**
117
- * Retry config applied to every `call()`.
118
- * Set to `false` to disable retries entirely.
119
- * @default { maxRetries: 3, baseDelayMs: 500 }
120
- */
121
- retry?: RetryConfig | false;
122
- /**
123
- * Per-request timeout in ms. Applies an `AbortSignal` timeout to `Connection`
124
- * calls where supported, and is used as a deadline for the health probe.
125
- * @default 30_000
126
- */
127
- requestTimeoutMs?: number;
128
- /**
129
- * Default Solana commitment level for connections.
130
- * @default "confirmed"
131
- */
132
- commitment?: Commitment;
133
- /**
134
- * If true, `console.warn` diagnostic messages on retries, failovers, etc.
135
- * @default true
136
- */
137
- verbose?: boolean;
138
- }
139
- /**
140
- * Result of an RPC health probe.
141
- *
142
- * @example
143
- * ```ts
144
- * import { checkRpcHealth } from "@percolator/sdk";
145
- *
146
- * const health = await checkRpcHealth("https://api.mainnet-beta.solana.com");
147
- * console.log(`Slot: ${health.slot}, Latency: ${health.latencyMs}ms`);
148
- * if (!health.healthy) console.warn(`Unhealthy: ${health.error}`);
149
- * ```
150
- */
151
- export interface RpcHealthResult {
152
- /** The endpoint that was probed. */
153
- endpoint: string;
154
- /** Whether the probe succeeded (getSlot returned without error). */
155
- healthy: boolean;
156
- /** Round-trip latency in milliseconds (0 if unhealthy). */
157
- latencyMs: number;
158
- /** Current slot height (0 if unhealthy). */
159
- slot: number;
160
- /** Error message if the probe failed. */
161
- error?: string;
162
- }
163
- /**
164
- * Probe an RPC endpoint's health by calling `getSlot()` and measuring latency.
165
- *
166
- * @param endpoint - RPC URL to probe
167
- * @param timeoutMs - Timeout in ms for the probe request (default: 5000)
168
- * @returns Health result with latency and slot height
169
- *
170
- * @example
171
- * ```ts
172
- * import { checkRpcHealth } from "@percolator/sdk";
173
- *
174
- * const result = await checkRpcHealth("https://api.mainnet-beta.solana.com", 3000);
175
- * if (result.healthy) {
176
- * console.log(`Slot ${result.slot} — ${result.latencyMs}ms`);
177
- * } else {
178
- * console.error(`RPC down: ${result.error}`);
179
- * }
180
- * ```
181
- */
182
- export declare function checkRpcHealth(endpoint: string, timeoutMs?: number): Promise<RpcHealthResult>;
183
- /** Resolved defaults for RetryConfig. */
184
- interface ResolvedRetryConfig {
185
- maxRetries: number;
186
- baseDelayMs: number;
187
- maxDelayMs: number;
188
- jitterFactor: number;
189
- retryableStatusCodes: number[];
190
- }
191
- declare function resolveRetryConfig(cfg?: RetryConfig | false): ResolvedRetryConfig | null;
192
- declare function normalizeEndpoint(ep: RpcEndpointConfig | string): RpcEndpointConfig;
193
- declare function endpointLabel(ep: RpcEndpointConfig): string;
194
- declare function isRetryable(err: unknown, codes: number[]): boolean;
195
- declare function computeDelay(attempt: number, config: ResolvedRetryConfig): number;
196
- /**
197
- * RPC connection pool with retry, failover, and round-robin support.
198
- *
199
- * Wraps one or more Solana RPC endpoints behind a single `call()` interface
200
- * that automatically retries transient errors and fails over to alternate
201
- * endpoints when one goes down.
202
- *
203
- * @example
204
- * ```ts
205
- * import { RpcPool } from "@percolator/sdk";
206
- *
207
- * const pool = new RpcPool({
208
- * endpoints: [
209
- * { url: "https://mainnet.helius-rpc.com/?api-key=KEY", weight: 10, label: "helius" },
210
- * { url: "https://api.mainnet-beta.solana.com", weight: 1, label: "public" },
211
- * ],
212
- * strategy: "failover",
213
- * retry: { maxRetries: 3 },
214
- * requestTimeoutMs: 30_000,
215
- * });
216
- *
217
- * // Execute any Connection method through the pool
218
- * const slot = await pool.call(conn => conn.getSlot());
219
- *
220
- * // Or get a raw connection for one-off use
221
- * const conn = pool.getConnection();
222
- *
223
- * // Health check all endpoints
224
- * const results = await pool.healthCheck();
225
- * ```
226
- */
227
- export declare class RpcPool {
228
- private readonly endpoints;
229
- private readonly strategy;
230
- private readonly retryConfig;
231
- private readonly requestTimeoutMs;
232
- private readonly verbose;
233
- /** Round-robin index tracker. */
234
- private rrIndex;
235
- /** Consecutive failure threshold before marking an endpoint unhealthy. */
236
- private static readonly UNHEALTHY_THRESHOLD;
237
- /** Minimum endpoints before auto-recovery is attempted. */
238
- private static readonly MIN_HEALTHY;
239
- constructor(config: RpcPoolConfig);
240
- /**
241
- * Execute a function against a pooled connection with automatic retry
242
- * and failover.
243
- *
244
- * @param fn - Async function that receives a `Connection` and returns a result.
245
- * @returns The result of `fn`.
246
- * @throws The last error if all retries and failovers are exhausted.
247
- *
248
- * @example
249
- * ```ts
250
- * const balance = await pool.call(c => c.getBalance(pubkey));
251
- * const markets = await pool.call(c => discoverMarkets(c, programId, opts));
252
- * ```
253
- */
254
- call<T>(fn: (connection: Connection) => Promise<T>): Promise<T>;
255
- /**
256
- * Get a raw `Connection` from the current preferred endpoint.
257
- * Useful when you need to pass a Connection to external code.
258
- *
259
- * NOTE: This bypasses retry and failover logic. Prefer `call()`.
260
- *
261
- * @returns Solana Connection from the current preferred endpoint.
262
- *
263
- * @example
264
- * ```ts
265
- * const conn = pool.getConnection();
266
- * const balance = await conn.getBalance(pubkey);
267
- * ```
268
- */
269
- getConnection(): Connection;
270
- /**
271
- * Run a health check against all endpoints in the pool.
272
- *
273
- * @param timeoutMs - Per-endpoint probe timeout (default: 5000)
274
- * @returns Array of health results, one per endpoint.
275
- *
276
- * @example
277
- * ```ts
278
- * const results = await pool.healthCheck();
279
- * for (const r of results) {
280
- * console.log(`${r.endpoint}: ${r.healthy ? 'UP' : 'DOWN'} (${r.latencyMs}ms, slot ${r.slot})`);
281
- * }
282
- * ```
283
- */
284
- healthCheck(timeoutMs?: number): Promise<RpcHealthResult[]>;
285
- /**
286
- * Get the number of endpoints in the pool.
287
- */
288
- get size(): number;
289
- /**
290
- * Get the number of currently healthy endpoints.
291
- */
292
- get healthyCount(): number;
293
- /**
294
- * Get endpoint labels and their current status.
295
- *
296
- * @returns Array of `{ label, url, healthy, failures, lastLatencyMs }`.
297
- */
298
- status(): Array<{
299
- label: string;
300
- url: string;
301
- healthy: boolean;
302
- failures: number;
303
- lastLatencyMs: number;
304
- }>;
305
- /**
306
- * Select the next endpoint based on strategy.
307
- * Returns -1 if no endpoint is available.
308
- */
309
- private selectEndpoint;
310
- /**
311
- * If all endpoints are unhealthy, reset them so we at least try again.
312
- */
313
- private maybeRecoverEndpoints;
314
- }
315
- /**
316
- * Execute an async function with exponential-backoff retry.
317
- *
318
- * Use this when you already have a `Connection` and just want retry logic
319
- * without a full pool.
320
- *
321
- * @param fn - Async function to execute
322
- * @param config - Retry configuration (default: 3 retries, 500ms base delay)
323
- * @returns Result of `fn`
324
- * @throws The last error if all retries are exhausted
325
- *
326
- * @example
327
- * ```ts
328
- * import { withRetry } from "@percolator/sdk";
329
- * import { Connection } from "@solana/web3.js";
330
- *
331
- * const conn = new Connection("https://api.mainnet-beta.solana.com");
332
- * const slot = await withRetry(
333
- * () => conn.getSlot(),
334
- * { maxRetries: 3, baseDelayMs: 1000 },
335
- * );
336
- * ```
337
- */
338
- export declare function withRetry<T>(fn: () => Promise<T>, config?: RetryConfig): Promise<T>;
339
- /** @internal — exposed for unit tests only */
340
- export declare const _internal: {
341
- readonly isRetryable: typeof isRetryable;
342
- readonly computeDelay: typeof computeDelay;
343
- readonly resolveRetryConfig: typeof resolveRetryConfig;
344
- readonly normalizeEndpoint: typeof normalizeEndpoint;
345
- readonly endpointLabel: typeof endpointLabel;
346
- };
347
- export {};
@@ -1,358 +0,0 @@
1
- import { Connection, PublicKey } from "@solana/web3.js";
2
- /**
3
- * Full slab layout descriptor. Returned by detectSlabLayout().
4
- * All engine field offsets are relative to engineOff.
5
- */
6
- export interface SlabLayout {
7
- version: 0 | 1 | 2;
8
- headerLen: number;
9
- configOffset: number;
10
- configLen: number;
11
- reservedOff: number;
12
- engineOff: number;
13
- accountSize: number;
14
- maxAccounts: number;
15
- bitmapWords: number;
16
- accountsOff: number;
17
- engineInsuranceOff: number;
18
- engineParamsOff: number;
19
- paramsSize: number;
20
- engineCurrentSlotOff: number;
21
- engineFundingIndexOff: number;
22
- engineLastFundingSlotOff: number;
23
- engineFundingRateBpsOff: number;
24
- engineMarkPriceOff: number;
25
- engineLastCrankSlotOff: number;
26
- engineMaxCrankStalenessOff: number;
27
- engineTotalOiOff: number;
28
- engineLongOiOff: number;
29
- engineShortOiOff: number;
30
- engineCTotOff: number;
31
- enginePnlPosTotOff: number;
32
- engineLiqCursorOff: number;
33
- engineGcCursorOff: number;
34
- engineLastSweepStartOff: number;
35
- engineLastSweepCompleteOff: number;
36
- engineCrankCursorOff: number;
37
- engineSweepStartIdxOff: number;
38
- engineLifetimeLiquidationsOff: number;
39
- engineLifetimeForceClosesOff: number;
40
- engineNetLpPosOff: number;
41
- engineLpSumAbsOff: number;
42
- engineLpMaxAbsOff: number;
43
- engineLpMaxAbsSweepOff: number;
44
- engineEmergencyOiModeOff: number;
45
- engineEmergencyStartSlotOff: number;
46
- engineLastBreakerSlotOff: number;
47
- engineBitmapOff: number;
48
- postBitmap: number;
49
- acctOwnerOff: number;
50
- hasInsuranceIsolation: boolean;
51
- engineInsuranceIsolatedOff: number;
52
- engineInsuranceIsolationBpsOff: number;
53
- }
54
- export declare const ENGINE_OFF = 600;
55
- export declare const ENGINE_MARK_PRICE_OFF = 400;
56
- /**
57
- * V2 slab tier sizes (small and large) for discovery.
58
- * V2 uses ENGINE_OFF=600, BITMAP_OFF=432, ACCOUNT_SIZE=248, postBitmap=18.
59
- * Sizes overlap with V1D (postBitmap=2) — disambiguation requires reading the version field.
60
- */
61
- export declare const SLAB_TIERS_V2: {
62
- readonly small: {
63
- readonly maxAccounts: 256;
64
- readonly dataSize: 65088;
65
- readonly label: "Small";
66
- readonly description: "256 slots (V2 BPF intermediate)";
67
- };
68
- readonly large: {
69
- readonly maxAccounts: 4096;
70
- readonly dataSize: 1025568;
71
- readonly label: "Large";
72
- readonly description: "4,096 slots (V2 BPF intermediate)";
73
- };
74
- };
75
- /**
76
- * V1M slab tier sizes — mainnet-deployed V1 program (ESa89R5).
77
- * ENGINE_OFF=640, BITMAP_OFF=726, ACCOUNT_SIZE=248, postBitmap=18.
78
- * Expanded RiskParams (336 bytes) and trade_twap runtime fields.
79
- * Confirmed by on-chain probing of slab 8NY7rvQ (SOL/USDC Perpetual, 257512 bytes).
80
- */
81
- export declare const SLAB_TIERS_V1M: Record<string, {
82
- maxAccounts: number;
83
- dataSize: number;
84
- label: string;
85
- description: string;
86
- }>;
87
- /**
88
- * V1M2 slab tier sizes — mainnet program rebuilt from main@4861c56 with 312-byte accounts.
89
- * ENGINE_OFF=616, BITMAP_OFF=1008 (empirically verified from CCTegYZ...).
90
- * Engine struct is layout-identical to V_ADL; differs only in engineOff (616 vs 624).
91
- * Sizes are unique from V_ADL after the bitmap correction: medium=323312 vs V_ADL=323320.
92
- */
93
- export declare const SLAB_TIERS_V1M2: Record<string, {
94
- maxAccounts: number;
95
- dataSize: number;
96
- label: string;
97
- description: string;
98
- }>;
99
- /**
100
- * V_ADL slab tier sizes — PERC-8270/8271 ADL-upgraded program.
101
- * ENGINE_OFF=624, BITMAP_OFF=1008, ACCOUNT_SIZE=312, postBitmap=18.
102
- * New account layout adds ADL tracking fields (+64 bytes/account including alignment padding).
103
- * BPF SLAB_LEN verified by cargo build-sbf in PERC-8271: large (4096) = 1288320 bytes.
104
- */
105
- export declare const SLAB_TIERS_V_ADL: Record<string, {
106
- maxAccounts: number;
107
- dataSize: number;
108
- label: string;
109
- description: string;
110
- }>;
111
- /**
112
- * V_SETDEXPOOL slab tier sizes — PERC-SetDexPool security fix.
113
- * ENGINE_OFF=632, BITMAP_OFF=1008, ACCOUNT_SIZE=312, CONFIG_LEN=528.
114
- * e.g. large (4096 accts) = 1288336 bytes.
115
- */
116
- export declare const SLAB_TIERS_V_SETDEXPOOL: Record<string, {
117
- maxAccounts: number;
118
- dataSize: number;
119
- label: string;
120
- description: string;
121
- }>;
122
- /**
123
- * V12_1 slab tier sizes — percolator-core v12.1 merge.
124
- * ENGINE_OFF=648, BITMAP_OFF=1016, ACCOUNT_SIZE=320.
125
- * Verified by cargo build-sbf compile-time assertions.
126
- */
127
- export declare const SLAB_TIERS_V12_1: Record<string, {
128
- maxAccounts: number;
129
- dataSize: number;
130
- label: string;
131
- description: string;
132
- }>;
133
- /**
134
- * Detect the slab layout version from the raw account data length.
135
- * Returns the full SlabLayout descriptor, or null if the size is unrecognised.
136
- * Checks V12_1, V_SETDEXPOOL, V1M2, V_ADL, V1M, V0, V1D, V1D-legacy, V1, and V1-legacy sizes.
137
- *
138
- * When `data` is provided and the size matches V1D, the version field at offset 8 is read
139
- * to disambiguate V2 slabs (which produce identical sizes to V1D with postBitmap=2).
140
- * V2 slabs have version===2 at offset 8 (u32 LE).
141
- *
142
- * @param dataLen - The slab account data length in bytes
143
- * @param data - Optional raw slab data for version-field disambiguation
144
- */
145
- export declare function detectSlabLayout(dataLen: number, data?: Uint8Array): SlabLayout | null;
146
- /**
147
- * Legacy detectLayout for backward compat.
148
- * Returns { bitmapWords, accountsOff, maxAccounts } or null.
149
- *
150
- * GH#1238: previously recomputed accountsOff with hardcoded postBitmap=18, which gave a value
151
- * 16 bytes too large for V1D slabs (which use postBitmap=2). Now delegates directly to the
152
- * SlabLayout descriptor so each variant uses its own correct accountsOff.
153
- */
154
- export declare function detectLayout(dataLen: number): {
155
- bitmapWords: number;
156
- accountsOff: number;
157
- maxAccounts: number;
158
- } | null;
159
- export interface SlabHeader {
160
- magic: bigint;
161
- version: number;
162
- bump: number;
163
- flags: number;
164
- resolved: boolean;
165
- paused: boolean;
166
- admin: PublicKey;
167
- nonce: bigint;
168
- lastThrUpdateSlot: bigint;
169
- }
170
- export interface MarketConfig {
171
- collateralMint: PublicKey;
172
- vaultPubkey: PublicKey;
173
- indexFeedId: PublicKey;
174
- maxStalenessSlots: bigint;
175
- confFilterBps: number;
176
- vaultAuthorityBump: number;
177
- invert: number;
178
- unitScale: number;
179
- fundingHorizonSlots: bigint;
180
- fundingKBps: bigint;
181
- fundingInvScaleNotionalE6: bigint;
182
- fundingMaxPremiumBps: bigint;
183
- fundingMaxBpsPerSlot: bigint;
184
- /** @deprecated Removed in V12_1 — always 0 */ fundingPremiumWeightBps: bigint;
185
- /** @deprecated Removed in V12_1 — always 0 */ fundingSettlementIntervalSlots: bigint;
186
- /** @deprecated Removed in V12_1 — always 0 */ fundingPremiumDampeningE6: bigint;
187
- /** @deprecated Removed in V12_1 — always 0 */ fundingPremiumMaxBpsPerSlot: bigint;
188
- threshFloor: bigint;
189
- threshRiskBps: bigint;
190
- threshUpdateIntervalSlots: bigint;
191
- threshStepBps: bigint;
192
- threshAlphaBps: bigint;
193
- threshMin: bigint;
194
- threshMax: bigint;
195
- threshMinStep: bigint;
196
- oracleAuthority: PublicKey;
197
- authorityPriceE6: bigint;
198
- authorityTimestamp: bigint;
199
- oraclePriceCapE2bps: bigint;
200
- lastEffectivePriceE6: bigint;
201
- oiCapMultiplierBps: bigint;
202
- maxPnlCap: bigint;
203
- adaptiveFundingEnabled: boolean;
204
- adaptiveScaleBps: number;
205
- adaptiveMaxFundingBps: bigint;
206
- marketCreatedSlot: bigint;
207
- oiRampSlots: bigint;
208
- resolvedSlot: bigint;
209
- insuranceIsolationBps: number;
210
- /** PERC-622: Oracle phase (0=Nascent, 1=Growing, 2=Mature) */
211
- oraclePhase: number;
212
- /** PERC-622: Cumulative trade volume in e6 format */
213
- cumulativeVolumeE6: bigint;
214
- /** PERC-622: Slots elapsed from market creation to Phase 2 entry (u24) */
215
- phase2DeltaSlots: number;
216
- /**
217
- * PERC-SetDexPool: Admin-pinned DEX pool pubkey for HYPERP markets.
218
- * Null when reading old slabs (pre-SetDexPool configLen < 528) or when
219
- * SetDexPool has never been called (all-zero pubkey).
220
- * Non-null means the program will reject any UpdateHyperpMark that passes
221
- * a different pool account.
222
- */
223
- dexPool: PublicKey | null;
224
- }
225
- export interface InsuranceFund {
226
- balance: bigint;
227
- feeRevenue: bigint;
228
- isolatedBalance: bigint;
229
- isolationBps: number;
230
- }
231
- export interface RiskParams {
232
- warmupPeriodSlots: bigint;
233
- maintenanceMarginBps: bigint;
234
- initialMarginBps: bigint;
235
- tradingFeeBps: bigint;
236
- maxAccounts: bigint;
237
- newAccountFee: bigint;
238
- riskReductionThreshold: bigint;
239
- maintenanceFeePerSlot: bigint;
240
- maxCrankStalenessSlots: bigint;
241
- liquidationFeeBps: bigint;
242
- liquidationFeeCap: bigint;
243
- liquidationBufferBps: bigint;
244
- minLiquidationAbs: bigint;
245
- }
246
- export interface EngineState {
247
- vault: bigint;
248
- insuranceFund: InsuranceFund;
249
- currentSlot: bigint;
250
- fundingIndexQpbE6: bigint;
251
- lastFundingSlot: bigint;
252
- fundingRateBpsPerSlotLast: bigint;
253
- lastCrankSlot: bigint;
254
- maxCrankStalenessSlots: bigint;
255
- totalOpenInterest: bigint;
256
- longOi: bigint;
257
- shortOi: bigint;
258
- cTot: bigint;
259
- pnlPosTot: bigint;
260
- liqCursor: number;
261
- gcCursor: number;
262
- lastSweepStartSlot: bigint;
263
- lastSweepCompleteSlot: bigint;
264
- crankCursor: number;
265
- sweepStartIdx: number;
266
- lifetimeLiquidations: bigint;
267
- lifetimeForceCloses: bigint;
268
- netLpPos: bigint;
269
- lpSumAbs: bigint;
270
- lpMaxAbs: bigint;
271
- lpMaxAbsSweep: bigint;
272
- emergencyOiMode: boolean;
273
- emergencyStartSlot: bigint;
274
- lastBreakerSlot: bigint;
275
- numUsedAccounts: number;
276
- nextAccountId: bigint;
277
- markPriceE6: bigint;
278
- }
279
- export declare enum AccountKind {
280
- User = 0,
281
- LP = 1
282
- }
283
- export interface Account {
284
- kind: AccountKind;
285
- accountId: bigint;
286
- capital: bigint;
287
- pnl: bigint;
288
- reservedPnl: bigint;
289
- warmupStartedAtSlot: bigint;
290
- warmupSlopePerStep: bigint;
291
- positionSize: bigint;
292
- entryPrice: bigint;
293
- fundingIndex: bigint;
294
- matcherProgram: PublicKey;
295
- matcherContext: PublicKey;
296
- owner: PublicKey;
297
- feeCredits: bigint;
298
- lastFeeSlot: bigint;
299
- }
300
- export declare function fetchSlab(connection: Connection, slabPubkey: PublicKey): Promise<Uint8Array>;
301
- export declare const RAMP_START_BPS = 1000n;
302
- export declare const DEFAULT_OI_RAMP_SLOTS = 432000n;
303
- export declare function computeEffectiveOiCapBps(config: MarketConfig, currentSlot: bigint): bigint;
304
- export declare function readNonce(data: Uint8Array): bigint;
305
- export declare function readLastThrUpdateSlot(data: Uint8Array): bigint;
306
- /**
307
- * Parse slab header (first 72 bytes — layout-independent).
308
- */
309
- export declare function parseHeader(data: Uint8Array): SlabHeader;
310
- /**
311
- * Parse market config. Layout-version aware.
312
- * For V0 slabs, fields beyond the basic config are read if present in the data,
313
- * otherwise defaults are returned.
314
- *
315
- * @param data - Slab data (may be a partial slice for discovery; pass layoutHint in that case)
316
- * @param layoutHint - Pre-detected layout to use; if omitted, detected from data.length.
317
- */
318
- export declare function parseConfig(data: Uint8Array, layoutHint?: SlabLayout | null): MarketConfig;
319
- /**
320
- * Parse RiskParams from engine data. Layout-version aware.
321
- * For V0 slabs, extended params (risk_threshold, maintenance_fee, etc.) are
322
- * not present on-chain, so defaults (0) are returned.
323
- *
324
- * @param data - Slab data (may be a partial slice; pass layoutHint in that case)
325
- * @param layoutHint - Pre-detected layout to use; if omitted, detected from data.length.
326
- */
327
- export declare function parseParams(data: Uint8Array, layoutHint?: SlabLayout | null): RiskParams;
328
- /**
329
- * Parse RiskEngine state (excluding accounts array). Layout-version aware.
330
- */
331
- export declare function parseEngine(data: Uint8Array): EngineState;
332
- /**
333
- * Read bitmap to get list of used account indices.
334
- */
335
- /**
336
- * Return all account indices whose bitmap bit is set (i.e. slot is in use).
337
- * Uses the layout-aware bitmap offset so V1_LEGACY slabs (bitmap at rel+672) are handled correctly.
338
- */
339
- export declare function parseUsedIndices(data: Uint8Array): number[];
340
- /**
341
- * Check if a specific account index is used.
342
- */
343
- export declare function isAccountUsed(data: Uint8Array, idx: number): boolean;
344
- /**
345
- * Calculate the maximum valid account index for a given slab size.
346
- */
347
- export declare function maxAccountIndex(dataLen: number): number;
348
- /**
349
- * Parse a single account by index.
350
- */
351
- export declare function parseAccount(data: Uint8Array, idx: number): Account;
352
- /**
353
- * Parse all used accounts.
354
- */
355
- export declare function parseAllAccounts(data: Uint8Array): {
356
- idx: number;
357
- account: Account;
358
- }[];