@thru/programs 0.2.37 → 0.2.39

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.
@@ -0,0 +1,1146 @@
1
+ import { Pubkey } from '@thru/sdk';
2
+ import { encodeAddress } from '@thru/sdk/helpers';
3
+ import type { Account } from '@thru/sdk';
4
+ import {
5
+ ArenaHeader,
6
+ CbookAccount,
7
+ CbookHeader,
8
+ CbookLevel,
9
+ ClobEvent,
10
+ ClobInstructionBuilder,
11
+ ClobProgramAccount,
12
+ CreateOrderEntryInstructionBuilder,
13
+ CreateSeatlessOrderEntryInstructionBuilder,
14
+ MarketAccount as MarketAccountView,
15
+ MarketCreateInstructionBuilder,
16
+ MarketRecordInstructionBuilder,
17
+ MarketSetStatusInstructionBuilder,
18
+ ModifyOrderEntryInstructionBuilder,
19
+ OrderArenaAccount,
20
+ OrderEntry as OrderEntryView,
21
+ SeatArenaAccount,
22
+ SeatCreateInstructionBuilder,
23
+ SeatEntry as SeatEntryView,
24
+ TokenTransferInstructionBuilder,
25
+ } from './abi/thru/program/clob/types';
26
+
27
+ export {
28
+ ArenaHeader,
29
+ ArenaHeaderBuilder,
30
+ CbookAccount,
31
+ CbookHeader,
32
+ CbookHeaderBuilder,
33
+ CbookLevel,
34
+ CbookLevelBuilder,
35
+ ClientId,
36
+ ClobError,
37
+ ClobErrorBuilder,
38
+ ClobEvent,
39
+ ClobEventBuilder,
40
+ ClobInstruction,
41
+ ClobInstructionBuilder,
42
+ ClobProgramAccount,
43
+ ClobProgramAccountBuilder,
44
+ CreateOrderEntryInstruction,
45
+ CreateOrderEntryInstructionBuilder,
46
+ CreateSeatlessOrderEntryInstruction,
47
+ CreateSeatlessOrderEntryInstructionBuilder,
48
+ MarketAccount as MarketAccountView,
49
+ MarketAccountBuilder,
50
+ MarketCreateInstruction,
51
+ MarketCreateInstructionBuilder,
52
+ MarketCreatedEvent,
53
+ MarketCreatedEventBuilder,
54
+ MarketRecordInstruction,
55
+ MarketRecordInstructionBuilder,
56
+ MarketSetStatusInstruction,
57
+ MarketSetStatusInstructionBuilder,
58
+ ModifyOrderEntryInstruction,
59
+ ModifyOrderEntryInstructionBuilder,
60
+ OrderArenaAccount,
61
+ OrderCancelledEvent,
62
+ OrderCancelledEventBuilder,
63
+ OrderEntry as OrderEntryView,
64
+ OrderEntryBuilder,
65
+ OrderEntryRemovedEvent,
66
+ OrderEntryRemovedEventBuilder,
67
+ OrderFilledEvent,
68
+ OrderFilledEventBuilder,
69
+ OrderModifiedEvent,
70
+ OrderModifiedEventBuilder,
71
+ OrderPostedEvent,
72
+ OrderPostedEventBuilder,
73
+ SeatArenaAccount,
74
+ SeatAssignedEvent,
75
+ SeatAssignedEventBuilder,
76
+ SeatCreateInstruction,
77
+ SeatCreateInstructionBuilder,
78
+ SeatEntry as SeatEntryView,
79
+ SeatEntryBuilder,
80
+ TokenBalanceEvent,
81
+ TokenBalanceEventBuilder,
82
+ TokenTransferInstruction,
83
+ TokenTransferInstructionBuilder,
84
+ } from './abi/thru/program/clob/types';
85
+
86
+ export const CLOB_INSTRUCTION_MARKET_RECORD = 0;
87
+ export const CLOB_INSTRUCTION_SEAT_CREATE = 1;
88
+ export const CLOB_INSTRUCTION_TOKEN_DEPOSIT = 2;
89
+ export const CLOB_INSTRUCTION_TOKEN_WITHDRAW = 3;
90
+ export const CLOB_INSTRUCTION_CREATE_ORDER_ENTRY = 4;
91
+ export const CLOB_INSTRUCTION_MODIFY_ORDER_ENTRY = 5;
92
+ export const CLOB_INSTRUCTION_MARKET_SET_STATUS = 8;
93
+ export const CLOB_INSTRUCTION_MARKET_CREATE = 9;
94
+ export const CLOB_INSTRUCTION_CREATE_SEATLESS_ORDER_ENTRY = 10;
95
+
96
+ export const CLOB_EVENT_SEAT_ASSIGNED = 1;
97
+ export const CLOB_EVENT_ORDER_CANCELLED = 2;
98
+ export const CLOB_EVENT_MARKET_CREATED = 3;
99
+ export const CLOB_EVENT_ORDER_FILLED = 4;
100
+ export const CLOB_EVENT_ORDER_POSTED = 5;
101
+ export const CLOB_EVENT_ORDER_ENTRY_REMOVED = 6;
102
+ export const CLOB_EVENT_ORDER_MODIFIED = 7;
103
+ export const CLOB_EVENT_TOKEN_DEPOSIT = 8;
104
+ export const CLOB_EVENT_TOKEN_WITHDRAW = 9;
105
+ export const CLOB_EVENT_MARKET_STATUS = 10;
106
+
107
+ export const CLOB_EVENT_SIDE_BUY = 0;
108
+ export const CLOB_EVENT_SIDE_SELL = 1;
109
+ export const CLOB_EVENT_TOKEN_SIDE_BASE = 0;
110
+ export const CLOB_EVENT_TOKEN_SIDE_QUOTE = 1;
111
+ export const CLOB_EVENT_REMOVE_REASON_FILLED = 0;
112
+ export const CLOB_EVENT_REMOVE_REASON_EXPIRED = 1;
113
+ export const CLOB_EVENT_REMOVE_REASON_EVICTED = 2;
114
+ export const CLOB_EVENT_REMOVE_REASON_USER = 3;
115
+
116
+ export const CLOB_STATUS_FLAG_PAUSED = 1 << 0;
117
+ export const CLOB_STATUS_FLAG_POST_ONLY = 1 << 1;
118
+ export const CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN = 1 << 2;
119
+ export const CLOB_STATUS_FLAG_DEPOSITS_FROZEN = 1 << 3;
120
+
121
+ export const CLOB_ORDER_TYPE_GTC = 0;
122
+ export const CLOB_ORDER_TYPE_MTL = 1;
123
+ export const CLOB_ORDER_TYPE_ALO = 2;
124
+ export const CLOB_ORDER_TYPE_IOC = 3;
125
+ export const CLOB_ORDER_TYPE_FOK = 4;
126
+
127
+ export const CLOB_ORDER_FLAG_BUY = 1 << 0;
128
+ export const CLOB_ORDER_FLAG_HAS_CLIENT_ID = 1 << 6;
129
+ export const CLOB_MODIFY_FLAG_FAIL_IF_OUT_OF_RANGE = 1 << 0;
130
+ export const CLOB_MODIFY_FLAG_HAS_CLIENT_ID = 1 << 1;
131
+ export const CLOB_MODIFY_FLAG_HAS_ORDER_ID = 1 << 2;
132
+
133
+ export const CLOB_MARKET_ACCOUNT_SIZE = 256;
134
+ export const CLOB_ARENA_HEADER_SIZE = 64;
135
+ export const CLOB_ORDER_ENTRY_SIZE = 64;
136
+ export const CLOB_SEAT_ENTRY_SIZE = 64;
137
+ export const CLOB_CBOOK_HEADER_SIZE = 16;
138
+ export const CLOB_CBOOK_LEVEL_SIZE = 8;
139
+ export const CLOB_CBOOK_MAX_SIZE = ((1 << 24) - CLOB_CBOOK_HEADER_SIZE) / CLOB_CBOOK_LEVEL_SIZE;
140
+ export const CLOB_CBOOK_EMPTY_PRICE_IN_TICKS = (1n << 64n) - 1n;
141
+ export const CLOB_CBOOK_MAX_PRICE_IN_TICKS = CLOB_CBOOK_EMPTY_PRICE_IN_TICKS - 2n - BigInt(CLOB_CBOOK_MAX_SIZE);
142
+ export const CLOB_CLIENT_ID_SIZE = 16;
143
+ export const CLOB_SEATLESS_SEAT_IDX = 1;
144
+ export const CLOB_NULL_INDEX = 0xfffff;
145
+
146
+ type ClobInstructionVariant =
147
+ | 'market_record'
148
+ | 'seat_create'
149
+ | 'token_deposit'
150
+ | 'token_withdraw'
151
+ | 'create_order_entry'
152
+ | 'modify_order_entry'
153
+ | 'market_set_status'
154
+ | 'market_create'
155
+ | 'create_seatless_order_entry';
156
+
157
+ export type ClobOrderSide = 'buy' | 'sell';
158
+ export type ClobOrderType = 'gtc' | 'mtl' | 'alo' | 'ioc' | 'fok';
159
+
160
+ export type AccountLookupContext = {
161
+ getAccountIndex: (pubkey: Uint8Array) => number;
162
+ };
163
+
164
+ export type InstructionData = (context: AccountLookupContext) => Promise<Uint8Array>;
165
+
166
+ export interface MarketRecordArgs {
167
+ marketRecordIndex: number;
168
+ seatArenaAccountBytes: Uint8Array;
169
+ orderArenaAccountBytes: Uint8Array;
170
+ bidsCbookAccountBytes: Uint8Array;
171
+ asksCbookAccountBytes: Uint8Array;
172
+ seatAuthorityAccountBytes?: Uint8Array;
173
+ seatIndex?: number;
174
+ tokenProgramAccountBytes: Uint8Array;
175
+ baseVaultAccountBytes: Uint8Array;
176
+ quoteVaultAccountBytes: Uint8Array;
177
+ marketAuthorityAccountBytes: Uint8Array;
178
+ }
179
+
180
+ export interface MarketCreateArgs extends MarketRecordArgs {
181
+ lotSize: bigint;
182
+ tickSize: bigint;
183
+ baseMintAccountBytes: Uint8Array;
184
+ quoteMintAccountBytes: Uint8Array;
185
+ seatArenaStateProof: Uint8Array;
186
+ orderArenaStateProof: Uint8Array;
187
+ bidsCbookStateProof: Uint8Array;
188
+ asksCbookStateProof: Uint8Array;
189
+ baseVaultStateProof: Uint8Array;
190
+ quoteVaultStateProof: Uint8Array;
191
+ }
192
+
193
+ export interface SeatCreateArgs {
194
+ marketRecordIndex: number;
195
+ seatAuthorityAccountBytes: Uint8Array;
196
+ }
197
+
198
+ export interface TokenTransferArgs {
199
+ marketRecordIndex: number;
200
+ tokenProgramAccountBytes: Uint8Array;
201
+ fromAccountBytes: Uint8Array;
202
+ toAccountBytes: Uint8Array;
203
+ amount: bigint;
204
+ }
205
+
206
+ export interface CreateOrderArgs {
207
+ marketRecordIndex: number;
208
+ side: ClobOrderSide;
209
+ orderType?: ClobOrderType;
210
+ price: bigint;
211
+ quantity: bigint;
212
+ expirationTime: bigint;
213
+ clientId?: Uint8Array;
214
+ discardAfterMatch?: boolean;
215
+ failIfOutsideBook?: boolean;
216
+ }
217
+
218
+ export interface CreateSeatlessOrderArgs {
219
+ marketRecordIndex: number;
220
+ side: ClobOrderSide;
221
+ orderType: 'ioc' | 'fok';
222
+ price: bigint;
223
+ quantity: bigint;
224
+ quoteWalletBytes: Uint8Array;
225
+ baseWalletBytes: Uint8Array;
226
+ clientId?: Uint8Array;
227
+ }
228
+
229
+ export interface ModifyOrderArgs {
230
+ marketRecordIndex: number;
231
+ orderEntryIndex: number;
232
+ quantity: bigint;
233
+ expirationTime: bigint;
234
+ failIfOutOfRange?: boolean;
235
+ clientId?: Uint8Array;
236
+ orderId?: bigint;
237
+ }
238
+
239
+ export interface MarketSetStatusArgs {
240
+ marketRecordIndex: number;
241
+ statusFlags: number;
242
+ }
243
+
244
+ export interface ClobMarket {
245
+ magic: number;
246
+ statusFlags: number;
247
+ lotSize: bigint;
248
+ tickSize: bigint;
249
+ nextOrderId: bigint;
250
+ orderEntry: string;
251
+ bidsCbook: string;
252
+ asksCbook: string;
253
+ tokenProgram: string;
254
+ baseVault: string;
255
+ quoteVault: string;
256
+ marketAuthority: string;
257
+ }
258
+
259
+ export interface ClobArenaHeader {
260
+ nextEntryIndex: number;
261
+ freeMagic: bigint;
262
+ }
263
+
264
+ export interface ClobArenaSlot<T> {
265
+ index: number;
266
+ active: boolean;
267
+ entry: T;
268
+ }
269
+
270
+ export interface ClobSeatEntry {
271
+ seatIndex: number;
272
+ seatAuthority: string;
273
+ quantityBase: bigint;
274
+ quantityQuote: bigint;
275
+ headOrderEntryIndex: number;
276
+ }
277
+
278
+ export interface ClobOrderEntry {
279
+ orderEntryIndex: number;
280
+ seatNextOrderEntryIndex: number;
281
+ seatPreviousOrderEntryIndex: number;
282
+ seatIndex: number;
283
+ levelNextOrderEntryIndex: number;
284
+ levelPreviousOrderEntryIndex: number;
285
+ levelIndex: number;
286
+ levelAccountIndex: number;
287
+ quantityInLots: bigint;
288
+ orderId: bigint;
289
+ clientId: Uint8Array;
290
+ expirationTime: bigint;
291
+ }
292
+
293
+ export interface ClobCbookLevel {
294
+ levelIndex: number;
295
+ headOrderEntryIndex: number;
296
+ tailOrderEntryIndex: number;
297
+ }
298
+
299
+ export interface ClobCbook {
300
+ bestLevelIndex: number;
301
+ bestPriceInTicks: bigint;
302
+ levels: ClobCbookLevel[];
303
+ }
304
+
305
+ export interface ClobOrderBookOrder {
306
+ side: ClobOrderSide;
307
+ priceInTicks: bigint;
308
+ quantityInLots: bigint;
309
+ orderId: bigint;
310
+ orderEntryIndex: number;
311
+ seatIndex: number;
312
+ clientId: Uint8Array;
313
+ expirationTime: bigint;
314
+ }
315
+
316
+ export interface ClobOrderBookLevel {
317
+ side: ClobOrderSide;
318
+ priceInTicks: bigint;
319
+ quantityInLots: bigint;
320
+ orders: ClobOrderBookOrder[];
321
+ }
322
+
323
+ export interface ClobOrderBookSnapshot {
324
+ bids: ClobOrderBookLevel[];
325
+ asks: ClobOrderBookLevel[];
326
+ bestBid: ClobOrderBookLevel | null;
327
+ bestAsk: ClobOrderBookLevel | null;
328
+ }
329
+
330
+
331
+ export type ClobTokenSide = 'base' | 'quote';
332
+ export type ClobOrderRemovalReason = 'filled' | 'expired' | 'evicted' | 'user';
333
+
334
+ export interface ParsedClobEventBase {
335
+ eventType: bigint;
336
+ variant: string;
337
+ payload: Uint8Array;
338
+ }
339
+
340
+ export type ParsedClobEvent =
341
+ | (ParsedClobEventBase & {
342
+ variant: 'seat_assigned';
343
+ seatIndex: number;
344
+ seatAuthority: string;
345
+ market: string;
346
+ })
347
+ | (ParsedClobEventBase & {
348
+ variant: 'order_cancelled';
349
+ seatIndex: number;
350
+ side: ClobOrderSide;
351
+ orderType: ClobOrderType;
352
+ price: bigint;
353
+ quantity: bigint;
354
+ clientId: Uint8Array;
355
+ market: string;
356
+ seatAuthority: string;
357
+ })
358
+ | (ParsedClobEventBase & {
359
+ variant: 'market_created';
360
+ lotSize: bigint;
361
+ tickSize: bigint;
362
+ baseMint: string;
363
+ quoteMint: string;
364
+ marketAuthority: string;
365
+ market: string;
366
+ orderArena: string;
367
+ bidsCbook: string;
368
+ asksCbook: string;
369
+ baseVault: string;
370
+ quoteVault: string;
371
+ })
372
+ | (ParsedClobEventBase & {
373
+ variant: 'order_filled';
374
+ takerSeatIndex: number;
375
+ makerSeatIndex: number;
376
+ takerSide: ClobOrderSide;
377
+ price: bigint;
378
+ quantity: bigint;
379
+ makerOrderId: bigint;
380
+ makerClientId: Uint8Array;
381
+ market: string;
382
+ takerSeatAuthority: string;
383
+ makerSeatAuthority: string;
384
+ })
385
+ | (ParsedClobEventBase & {
386
+ variant: 'order_posted';
387
+ seatIndex: number;
388
+ side: ClobOrderSide;
389
+ orderType: ClobOrderType;
390
+ price: bigint;
391
+ quantity: bigint;
392
+ orderId: bigint;
393
+ clientId: Uint8Array;
394
+ market: string;
395
+ seatAuthority: string;
396
+ })
397
+ | (ParsedClobEventBase & {
398
+ variant: 'order_entry_removed';
399
+ seatIndex: number;
400
+ side: ClobOrderSide;
401
+ reason: ClobOrderRemovalReason;
402
+ price: bigint;
403
+ quantity: bigint;
404
+ orderId: bigint;
405
+ clientId: Uint8Array;
406
+ market: string;
407
+ seatAuthority: string;
408
+ })
409
+ | (ParsedClobEventBase & {
410
+ variant: 'order_modified';
411
+ seatIndex: number;
412
+ side: ClobOrderSide;
413
+ price: bigint;
414
+ quantity: bigint;
415
+ orderId: bigint;
416
+ clientId: Uint8Array;
417
+ expirationTime: bigint;
418
+ market: string;
419
+ seatAuthority: string;
420
+ })
421
+ | (ParsedClobEventBase & {
422
+ variant: 'token_deposit' | 'token_withdraw';
423
+ seatIndex: number;
424
+ tokenSide: ClobTokenSide;
425
+ amount: bigint;
426
+ quantityBase: bigint;
427
+ quantityQuote: bigint;
428
+ market: string;
429
+ seatAuthority: string;
430
+ wallet: string;
431
+ vault: string;
432
+ })
433
+ | (ParsedClobEventBase & {
434
+ variant: 'market_status';
435
+ statusFlags: number;
436
+ market: string;
437
+ marketAuthority: string;
438
+ });
439
+
440
+ export function createMarketRecordInstruction(args: MarketRecordArgs): InstructionData {
441
+ return async (context) => {
442
+ const payload = new MarketRecordInstructionBuilder()
443
+ .set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
444
+ .set_seat_arena_account_idx(accountIndex(context, args.seatArenaAccountBytes))
445
+ .set_order_arena_account_idx(accountIndex(context, args.orderArenaAccountBytes))
446
+ .set_bids_cbook_account_idx(accountIndex(context, args.bidsCbookAccountBytes))
447
+ .set_asks_cbook_account_idx(accountIndex(context, args.asksCbookAccountBytes))
448
+ .set_seat_authority_account_idx(optionalAccountIndex(context, args.seatAuthorityAccountBytes))
449
+ .set_seat_idx(args.seatIndex ?? CLOB_NULL_INDEX)
450
+ .set_token_program_idx(accountIndex(context, args.tokenProgramAccountBytes))
451
+ .set_base_vault_account_idx(accountIndex(context, args.baseVaultAccountBytes))
452
+ .set_quote_vault_account_idx(accountIndex(context, args.quoteVaultAccountBytes))
453
+ .set_market_authority_account_idx(accountIndex(context, args.marketAuthorityAccountBytes))
454
+ .build();
455
+ return buildClobInstruction('market_record', payload);
456
+ };
457
+ }
458
+
459
+ export function createMarketCreateInstruction(args: MarketCreateArgs): InstructionData {
460
+ return async (context) => {
461
+ assertU64(args.lotSize, 'lotSize');
462
+ assertU64(args.tickSize, 'tickSize');
463
+ const builder = new MarketCreateInstructionBuilder()
464
+ .set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
465
+ .set_reserved0([0, 0, 0, 0, 0, 0])
466
+ .set_lot_size(args.lotSize)
467
+ .set_tick_size(args.tickSize)
468
+ .set_token_program_idx(accountIndex(context, args.tokenProgramAccountBytes))
469
+ .set_base_mint_idx(accountIndex(context, args.baseMintAccountBytes))
470
+ .set_quote_mint_idx(accountIndex(context, args.quoteMintAccountBytes))
471
+ .set_seat_arena_account_idx(accountIndex(context, args.seatArenaAccountBytes))
472
+ .set_order_arena_account_idx(accountIndex(context, args.orderArenaAccountBytes))
473
+ .set_bids_cbook_account_idx(accountIndex(context, args.bidsCbookAccountBytes))
474
+ .set_asks_cbook_account_idx(accountIndex(context, args.asksCbookAccountBytes))
475
+ .set_base_vault_account_idx(accountIndex(context, args.baseVaultAccountBytes))
476
+ .set_quote_vault_account_idx(accountIndex(context, args.quoteVaultAccountBytes))
477
+ .set_market_authority_account_idx(accountIndex(context, args.marketAuthorityAccountBytes));
478
+ builder.proof_seat_arena().write(args.seatArenaStateProof).finish();
479
+ builder.proof_order_arena().write(args.orderArenaStateProof).finish();
480
+ builder.proof_bids_cbook().write(args.bidsCbookStateProof).finish();
481
+ builder.proof_asks_cbook().write(args.asksCbookStateProof).finish();
482
+ builder.proof_base_vault().write(args.baseVaultStateProof).finish();
483
+ builder.proof_quote_vault().write(args.quoteVaultStateProof).finish();
484
+ return buildClobInstruction('market_create', builder.build());
485
+ };
486
+ }
487
+
488
+ export function createSeatCreateInstruction(args: SeatCreateArgs): InstructionData {
489
+ return async (context) => {
490
+ const payload = new SeatCreateInstructionBuilder()
491
+ .set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
492
+ .set_seat_authority_account_idx(accountIndex(context, args.seatAuthorityAccountBytes))
493
+ .set_reserved0([0, 0, 0, 0])
494
+ .build();
495
+ return buildClobInstruction('seat_create', payload);
496
+ };
497
+ }
498
+
499
+ export function createTokenDepositInstruction(args: TokenTransferArgs): InstructionData {
500
+ return createTokenTransferInstruction('token_deposit', args);
501
+ }
502
+
503
+ export function createTokenWithdrawInstruction(args: TokenTransferArgs): InstructionData {
504
+ return createTokenTransferInstruction('token_withdraw', args);
505
+ }
506
+
507
+ export function createOrderEntryInstruction(args: CreateOrderArgs): InstructionData {
508
+ return async () => {
509
+ const flags = orderFlags(args);
510
+ assertU64(args.price, 'price');
511
+ assertU64(args.quantity, 'quantity');
512
+ const builder = new CreateOrderEntryInstructionBuilder()
513
+ .set_instruction_flags(flags)
514
+ .set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
515
+ .set_reserved0([0, 0, 0, 0, 0])
516
+ .set_price(args.price)
517
+ .set_quantity(args.quantity)
518
+ .set_exp_time(args.expirationTime);
519
+ if (args.clientId) builder.client_id().write(assertClientId(args.clientId)).finish();
520
+ return buildClobInstruction('create_order_entry', builder.build());
521
+ };
522
+ }
523
+
524
+ export function createSeatlessOrderEntryInstruction(args: CreateSeatlessOrderArgs): InstructionData {
525
+ return async (context) => {
526
+ const flags = orderFlags(args);
527
+ assertU64(args.price, 'price');
528
+ assertU64(args.quantity, 'quantity');
529
+ const builder = new CreateSeatlessOrderEntryInstructionBuilder()
530
+ .set_instruction_flags(flags)
531
+ .set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
532
+ .set_reserved0([0, 0, 0, 0, 0])
533
+ .set_price(args.price)
534
+ .set_quantity(args.quantity)
535
+ .set_quote_wallet_idx(accountIndex(context, args.quoteWalletBytes))
536
+ .set_base_wallet_idx(accountIndex(context, args.baseWalletBytes))
537
+ .set_reserved1([0, 0, 0, 0]);
538
+ if (args.clientId) builder.client_id().write(assertClientId(args.clientId)).finish();
539
+ return buildClobInstruction('create_seatless_order_entry', builder.build());
540
+ };
541
+ }
542
+
543
+ export function createModifyOrderEntryInstruction(args: ModifyOrderArgs): InstructionData {
544
+ return async () => {
545
+ let flags = args.failIfOutOfRange ? CLOB_MODIFY_FLAG_FAIL_IF_OUT_OF_RANGE : 0;
546
+ if (args.clientId) flags |= CLOB_MODIFY_FLAG_HAS_CLIENT_ID;
547
+ if (args.orderId !== undefined) flags |= CLOB_MODIFY_FLAG_HAS_ORDER_ID;
548
+ const metadata = buildModifyOrderMetadata(args);
549
+ assertU64(args.quantity, 'quantity');
550
+ const builder = new ModifyOrderEntryInstructionBuilder()
551
+ .set_instruction_flags(flags)
552
+ .set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
553
+ .set_reserved0(0)
554
+ .set_order_entry_idx(args.orderEntryIndex)
555
+ .set_quantity(args.quantity)
556
+ .set_exp_time(args.expirationTime);
557
+ if (metadata.length) builder.metadata().write(metadata).finish();
558
+ return buildClobInstruction('modify_order_entry', builder.build());
559
+ };
560
+ }
561
+
562
+ export function createMarketSetStatusInstruction(args: MarketSetStatusArgs): InstructionData {
563
+ return async () => {
564
+ const payload = new MarketSetStatusInstructionBuilder()
565
+ .set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
566
+ .set_status_flags(assertU8(args.statusFlags, 'statusFlags'))
567
+ .set_reserved0([0, 0, 0, 0, 0])
568
+ .build();
569
+ return buildClobInstruction('market_set_status', payload);
570
+ };
571
+ }
572
+
573
+ export function parseClobProgramAccount(accountOrData: Account | Uint8Array): ClobMarket {
574
+ const data = accountData(accountOrData, 'CLOB program account');
575
+ const parsed = ClobProgramAccount.from_array(data);
576
+ if (!parsed) throw new Error('CLOB program account data is malformed');
577
+ return marketFromView(parsed.get_market());
578
+ }
579
+
580
+ export function parseMarketAccount(accountOrData: Account | Uint8Array): ClobMarket {
581
+ const data = accountData(accountOrData, 'CLOB market account');
582
+ const parsed = MarketAccountView.from_array(data);
583
+ if (!parsed) throw new Error('CLOB market account data is malformed');
584
+ return marketFromView(parsed);
585
+ }
586
+
587
+ export function parseSeatArenaAccount(accountOrData: Account | Uint8Array): {
588
+ market: ClobMarket;
589
+ header: ClobArenaHeader;
590
+ slots: ClobArenaSlot<ClobSeatEntry>[];
591
+ seats: ClobSeatEntry[];
592
+ seatlessSeat: ClobArenaSlot<ClobSeatEntry> | null;
593
+ } {
594
+ const data = accountData(accountOrData, 'CLOB seat arena account');
595
+ const parsed = SeatArenaAccount.from_array(data);
596
+ if (!parsed) throw new Error('CLOB seat arena account data is malformed');
597
+ const slots = parsed.get_entries().map((entry, idx) => {
598
+ const arenaIndex = idx + 1;
599
+ return {
600
+ index: arenaIndex,
601
+ active: isActiveSeatEntry(entry),
602
+ entry: seatEntryFromView(entry, arenaIndex),
603
+ };
604
+ });
605
+ const seatlessSeat = slots.find((slot) => slot.index === CLOB_SEATLESS_SEAT_IDX && slot.active) ?? null;
606
+ return {
607
+ market: marketFromView(parsed.get_market()),
608
+ header: arenaHeaderFromView(parsed.get_header()),
609
+ slots,
610
+ seats: slots
611
+ .filter((slot) => slot.active && slot.index !== CLOB_SEATLESS_SEAT_IDX)
612
+ .map((slot) => slot.entry),
613
+ seatlessSeat,
614
+ };
615
+ }
616
+
617
+ export function parseOrderArenaAccount(accountOrData: Account | Uint8Array): {
618
+ header: ClobArenaHeader;
619
+ slots: ClobArenaSlot<ClobOrderEntry>[];
620
+ orders: ClobOrderEntry[];
621
+ } {
622
+ const data = accountData(accountOrData, 'CLOB order arena account');
623
+ const parsed = OrderArenaAccount.from_array(data);
624
+ if (!parsed) throw new Error('CLOB order arena account data is malformed');
625
+ const slots = parsed.get_entries().map((entry, idx) => {
626
+ const arenaIndex = idx + 1;
627
+ return {
628
+ index: arenaIndex,
629
+ active: isActiveOrderEntry(entry),
630
+ entry: orderEntryFromView(entry, arenaIndex),
631
+ };
632
+ });
633
+ return {
634
+ header: arenaHeaderFromView(parsed.get_header()),
635
+ slots,
636
+ orders: slots.filter((slot) => slot.active).map((slot) => slot.entry),
637
+ };
638
+ }
639
+
640
+ export function parseCbookAccount(accountOrData: Account | Uint8Array): ClobCbook {
641
+ const data = accountData(accountOrData, 'CLOB cbook account');
642
+ const parsed = CbookAccount.from_array(data);
643
+ if (!parsed) throw new Error('CLOB cbook account data is malformed');
644
+ const header = parsed.get_header();
645
+ return {
646
+ bestLevelIndex: header.get_best_level_idx(),
647
+ bestPriceInTicks: header.get_best_price_in_ticks(),
648
+ levels: parsed.get_levels().map((level, idx) => cbookLevelFromView(level, idx)),
649
+ };
650
+ }
651
+
652
+ export function buildOrderBookSnapshot(args: {
653
+ bids: Array<ClobOrderBookOrder | ClobOrderEntry>;
654
+ asks: Array<ClobOrderBookOrder | ClobOrderEntry>;
655
+ bidsCbook?: ClobCbook;
656
+ asksCbook?: ClobCbook;
657
+ bidPrices?: Map<number, bigint> | Record<number, bigint>;
658
+ askPrices?: Map<number, bigint> | Record<number, bigint>;
659
+ }): ClobOrderBookSnapshot {
660
+ const bids = groupByPrice(args.bids.map((order) => normalizeBookOrder(order, 'buy', args.bidsCbook, args.bidPrices)), 'buy');
661
+ const asks = groupByPrice(args.asks.map((order) => normalizeBookOrder(order, 'sell', args.asksCbook, args.askPrices)), 'sell');
662
+ return {
663
+ bids,
664
+ asks,
665
+ bestBid: bids[0] ?? null,
666
+ bestAsk: asks[0] ?? null,
667
+ };
668
+ }
669
+
670
+ export function parseClobEvent(data: Uint8Array): ParsedClobEvent {
671
+ const parsed = ClobEvent.from_array(data);
672
+ if (!parsed) throw new Error('CLOB event data is malformed');
673
+ const variant = parsed.payloadVariant();
674
+ if (!variant) throw new Error('CLOB event type is unknown');
675
+
676
+ const eventType = parsed.get_event_type();
677
+ const payload = parsed.payload();
678
+ const base = {
679
+ eventType,
680
+ variant: variant.name,
681
+ payload: payload.bytes(),
682
+ };
683
+
684
+ switch (variant.name) {
685
+ case 'seat_assigned': {
686
+ const event = payload.asSeatAssigned();
687
+ if (!event) throw new Error('CLOB seat_assigned event payload is malformed');
688
+ return {
689
+ ...base,
690
+ variant: 'seat_assigned',
691
+ seatIndex: event.get_seat_idx(),
692
+ seatAuthority: pubkeyViewToAddress(event.get_seat_authority()),
693
+ market: pubkeyViewToAddress(event.get_market()),
694
+ };
695
+ }
696
+ case 'order_cancelled': {
697
+ const event = payload.asOrderCancelled();
698
+ if (!event) throw new Error('CLOB order_cancelled event payload is malformed');
699
+ return {
700
+ ...base,
701
+ variant: 'order_cancelled',
702
+ seatIndex: event.get_seat_idx(),
703
+ side: eventSideFromValue(event.get_side()),
704
+ orderType: orderTypeFromValue(event.get_order_type()),
705
+ price: event.get_price(),
706
+ quantity: event.get_qty(),
707
+ clientId: bytesFromView(event.get_client_id()),
708
+ market: pubkeyViewToAddress(event.get_market()),
709
+ seatAuthority: pubkeyViewToAddress(event.get_seat_authority()),
710
+ };
711
+ }
712
+ case 'market_created': {
713
+ const event = payload.asMarketCreated();
714
+ if (!event) throw new Error('CLOB market_created event payload is malformed');
715
+ return {
716
+ ...base,
717
+ variant: 'market_created',
718
+ lotSize: event.get_lot_size(),
719
+ tickSize: event.get_tick_size(),
720
+ baseMint: pubkeyViewToAddress(event.get_base_mint()),
721
+ quoteMint: pubkeyViewToAddress(event.get_quote_mint()),
722
+ marketAuthority: pubkeyViewToAddress(event.get_market_authority()),
723
+ market: pubkeyViewToAddress(event.get_market()),
724
+ orderArena: pubkeyViewToAddress(event.get_order_arena()),
725
+ bidsCbook: pubkeyViewToAddress(event.get_bids_cbook()),
726
+ asksCbook: pubkeyViewToAddress(event.get_asks_cbook()),
727
+ baseVault: pubkeyViewToAddress(event.get_base_vault()),
728
+ quoteVault: pubkeyViewToAddress(event.get_quote_vault()),
729
+ };
730
+ }
731
+ case 'order_filled': {
732
+ const event = payload.asOrderFilled();
733
+ if (!event) throw new Error('CLOB order_filled event payload is malformed');
734
+ return {
735
+ ...base,
736
+ variant: 'order_filled',
737
+ takerSeatIndex: event.get_taker_seat_idx(),
738
+ makerSeatIndex: event.get_maker_seat_idx(),
739
+ takerSide: eventSideFromValue(event.get_taker_side()),
740
+ price: event.get_price(),
741
+ quantity: event.get_qty(),
742
+ makerOrderId: event.get_maker_order_id(),
743
+ makerClientId: bytesFromView(event.get_maker_client_id()),
744
+ market: pubkeyViewToAddress(event.get_market()),
745
+ takerSeatAuthority: pubkeyViewToAddress(event.get_taker_seat_authority()),
746
+ makerSeatAuthority: pubkeyViewToAddress(event.get_maker_seat_authority()),
747
+ };
748
+ }
749
+ case 'order_posted': {
750
+ const event = payload.asOrderPosted();
751
+ if (!event) throw new Error('CLOB order_posted event payload is malformed');
752
+ return {
753
+ ...base,
754
+ variant: 'order_posted',
755
+ seatIndex: event.get_seat_idx(),
756
+ side: eventSideFromValue(event.get_side()),
757
+ orderType: orderTypeFromValue(event.get_order_type()),
758
+ price: event.get_price(),
759
+ quantity: event.get_qty(),
760
+ orderId: event.get_order_id(),
761
+ clientId: bytesFromView(event.get_client_id()),
762
+ market: pubkeyViewToAddress(event.get_market()),
763
+ seatAuthority: pubkeyViewToAddress(event.get_seat_authority()),
764
+ };
765
+ }
766
+ case 'order_entry_removed': {
767
+ const event = payload.asOrderEntryRemoved();
768
+ if (!event) throw new Error('CLOB order_entry_removed event payload is malformed');
769
+ return {
770
+ ...base,
771
+ variant: 'order_entry_removed',
772
+ seatIndex: event.get_seat_idx(),
773
+ side: eventSideFromValue(event.get_side()),
774
+ reason: removalReasonFromValue(event.get_reason()),
775
+ price: event.get_price(),
776
+ quantity: event.get_qty(),
777
+ orderId: event.get_order_id(),
778
+ clientId: bytesFromView(event.get_client_id()),
779
+ market: pubkeyViewToAddress(event.get_market()),
780
+ seatAuthority: pubkeyViewToAddress(event.get_seat_authority()),
781
+ };
782
+ }
783
+ case 'order_modified': {
784
+ const event = payload.asOrderModified();
785
+ if (!event) throw new Error('CLOB order_modified event payload is malformed');
786
+ return {
787
+ ...base,
788
+ variant: 'order_modified',
789
+ seatIndex: event.get_seat_idx(),
790
+ side: eventSideFromValue(event.get_side()),
791
+ price: event.get_price(),
792
+ quantity: event.get_qty(),
793
+ orderId: event.get_order_id(),
794
+ clientId: bytesFromView(event.get_client_id()),
795
+ expirationTime: event.get_exp_time(),
796
+ market: pubkeyViewToAddress(event.get_market()),
797
+ seatAuthority: pubkeyViewToAddress(event.get_seat_authority()),
798
+ };
799
+ }
800
+ case 'token_deposit':
801
+ case 'token_withdraw': {
802
+ const event = variant.name === 'token_deposit' ? payload.asTokenDeposit() : payload.asTokenWithdraw();
803
+ if (!event) throw new Error(`CLOB ${variant.name} event payload is malformed`);
804
+ return {
805
+ ...base,
806
+ variant: variant.name,
807
+ seatIndex: event.get_seat_idx(),
808
+ tokenSide: tokenSideFromValue(event.get_token_side()),
809
+ amount: event.get_amount(),
810
+ quantityBase: event.get_quantity_base(),
811
+ quantityQuote: event.get_quantity_quote(),
812
+ market: pubkeyViewToAddress(event.get_market()),
813
+ seatAuthority: pubkeyViewToAddress(event.get_seat_authority()),
814
+ wallet: pubkeyViewToAddress(event.get_wallet()),
815
+ vault: pubkeyViewToAddress(event.get_vault()),
816
+ };
817
+ }
818
+ case 'market_status': {
819
+ const event = payload.asMarketStatus();
820
+ if (!event) throw new Error('CLOB market_status event payload is malformed');
821
+ return {
822
+ ...base,
823
+ variant: 'market_status',
824
+ statusFlags: event.get_status_flags(),
825
+ market: pubkeyViewToAddress(event.get_market()),
826
+ marketAuthority: pubkeyViewToAddress(event.get_market_authority()),
827
+ };
828
+ }
829
+ default:
830
+ throw new Error('CLOB event type is unsupported');
831
+ }
832
+ }
833
+
834
+ export function encodeOrderFlags(args: {
835
+ side: ClobOrderSide;
836
+ orderType?: ClobOrderType;
837
+ clientId?: Uint8Array;
838
+ discardAfterMatch?: boolean;
839
+ failIfOutsideBook?: boolean;
840
+ }): number {
841
+ return orderFlags(args);
842
+ }
843
+
844
+ function buildModifyOrderMetadata(args: ModifyOrderArgs): Uint8Array {
845
+ const metadata = new Uint8Array((args.clientId ? CLOB_CLIENT_ID_SIZE : 0) + (args.orderId !== undefined ? 8 : 0));
846
+ let offset = 0;
847
+ if (args.clientId) {
848
+ metadata.set(assertClientId(args.clientId), offset);
849
+ offset += CLOB_CLIENT_ID_SIZE;
850
+ }
851
+ if (args.orderId !== undefined) {
852
+ assertU64(args.orderId, 'orderId');
853
+ new DataView(metadata.buffer).setBigUint64(offset, args.orderId, true);
854
+ }
855
+ return metadata;
856
+ }
857
+
858
+ function createTokenTransferInstruction(
859
+ variant: 'token_deposit' | 'token_withdraw',
860
+ args: TokenTransferArgs
861
+ ): InstructionData {
862
+ return async (context) => {
863
+ assertU64(args.amount, 'amount');
864
+ const payload = new TokenTransferInstructionBuilder()
865
+ .set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
866
+ .set_token_program_idx(accountIndex(context, args.tokenProgramAccountBytes))
867
+ .set_reserved0([0, 0, 0, 0])
868
+ .set_amount(args.amount)
869
+ .set_from_account_idx(accountIndex(context, args.fromAccountBytes))
870
+ .set_to_account_idx(accountIndex(context, args.toAccountBytes))
871
+ .set_reserved1([0, 0, 0, 0])
872
+ .build();
873
+ return buildClobInstruction(variant, payload);
874
+ };
875
+ }
876
+
877
+ function buildClobInstruction(variant: ClobInstructionVariant, payload: Uint8Array): Uint8Array {
878
+ const builder = new ClobInstructionBuilder();
879
+ builder.payload().select(variant).writePayload(payload).finish();
880
+ return builder.build();
881
+ }
882
+
883
+ function orderFlags(args: {
884
+ side: ClobOrderSide;
885
+ orderType?: ClobOrderType;
886
+ clientId?: Uint8Array;
887
+ discardAfterMatch?: boolean;
888
+ failIfOutsideBook?: boolean;
889
+ }): number {
890
+ let flags = args.side === 'buy' ? CLOB_ORDER_FLAG_BUY : 0;
891
+ flags |= orderTypeValue(args.orderType ?? 'gtc') << 1;
892
+ if (args.discardAfterMatch) flags |= 1 << 4;
893
+ if (args.failIfOutsideBook) flags |= 1 << 5;
894
+ if (args.clientId) flags |= CLOB_ORDER_FLAG_HAS_CLIENT_ID;
895
+ return flags;
896
+ }
897
+
898
+ function orderTypeValue(orderType: ClobOrderType): number {
899
+ switch (orderType) {
900
+ case 'gtc': return CLOB_ORDER_TYPE_GTC;
901
+ case 'mtl': return CLOB_ORDER_TYPE_MTL;
902
+ case 'alo': return CLOB_ORDER_TYPE_ALO;
903
+ case 'ioc': return CLOB_ORDER_TYPE_IOC;
904
+ case 'fok': return CLOB_ORDER_TYPE_FOK;
905
+ }
906
+ }
907
+
908
+ function marketFromView(view: MarketAccountView): ClobMarket {
909
+ return {
910
+ magic: view.get_magic(),
911
+ statusFlags: view.get_status_flags(),
912
+ lotSize: view.get_lot_size(),
913
+ tickSize: view.get_tick_size(),
914
+ nextOrderId: view.get_next_order_id(),
915
+ orderEntry: pubkeyViewToAddress(view.get_order_entry_pubkey()),
916
+ bidsCbook: pubkeyViewToAddress(view.get_bids_cbook_pubkey()),
917
+ asksCbook: pubkeyViewToAddress(view.get_asks_cbook_pubkey()),
918
+ tokenProgram: pubkeyViewToAddress(view.get_token_program_pubkey()),
919
+ baseVault: pubkeyViewToAddress(view.get_base_vault_pubkey()),
920
+ quoteVault: pubkeyViewToAddress(view.get_quote_vault_pubkey()),
921
+ marketAuthority: pubkeyViewToAddress(view.get_market_authority_pubkey()),
922
+ };
923
+ }
924
+
925
+ function arenaHeaderFromView(view: ArenaHeader): ClobArenaHeader {
926
+ return {
927
+ nextEntryIndex: view.get_next_entry_idx(),
928
+ freeMagic: view.get_free_magic(),
929
+ };
930
+ }
931
+
932
+ function isActiveSeatEntry(view: SeatEntryView): boolean {
933
+ return view.get_non_nullable_reserved() !== 0n;
934
+ }
935
+
936
+ function isActiveOrderEntry(view: OrderEntryView): boolean {
937
+ return view.get_expiry() !== 0n;
938
+ }
939
+
940
+ function seatEntryFromView(view: SeatEntryView, seatIndex: number): ClobSeatEntry {
941
+ return {
942
+ seatIndex,
943
+ seatAuthority: pubkeyViewToAddress(view.get_seat_authority_pubkey()),
944
+ quantityBase: view.get_quantity_base(),
945
+ quantityQuote: view.get_quantity_quote(),
946
+ headOrderEntryIndex: view.get_head_order_entry_idx(),
947
+ };
948
+ }
949
+
950
+ function orderEntryFromView(view: OrderEntryView, orderEntryIndex: number): ClobOrderEntry {
951
+ const seatPtrs = view.get_seat_ptrs();
952
+ const levelPtrs = view.get_level_ptrs();
953
+ return {
954
+ orderEntryIndex,
955
+ seatNextOrderEntryIndex: bitField(seatPtrs, 0n, 20n),
956
+ seatPreviousOrderEntryIndex: bitField(seatPtrs, 20n, 40n),
957
+ seatIndex: bitField(seatPtrs, 40n, 60n),
958
+ levelNextOrderEntryIndex: bitField(levelPtrs, 0n, 20n),
959
+ levelPreviousOrderEntryIndex: bitField(levelPtrs, 20n, 40n),
960
+ levelIndex: bitField(levelPtrs, 40n, 60n),
961
+ levelAccountIndex: bitField(levelPtrs, 60n, 64n),
962
+ quantityInLots: view.get_qty_in_lots(),
963
+ orderId: view.get_order_id(),
964
+ clientId: bytesFromView(view.get_client_id()),
965
+ expirationTime: view.get_expiry(),
966
+ };
967
+ }
968
+
969
+ function cbookLevelFromView(view: CbookLevel, levelIndex: number): ClobCbookLevel {
970
+ return {
971
+ levelIndex,
972
+ headOrderEntryIndex: view.get_head_entry_idx(),
973
+ tailOrderEntryIndex: view.get_tail_entry_idx(),
974
+ };
975
+ }
976
+
977
+ function normalizeBookOrder(
978
+ order: ClobOrderBookOrder | ClobOrderEntry,
979
+ side: ClobOrderSide,
980
+ cbook?: ClobCbook,
981
+ prices?: Map<number, bigint> | Record<number, bigint>
982
+ ): ClobOrderBookOrder {
983
+ if ('priceInTicks' in order) return order;
984
+ return {
985
+ side,
986
+ priceInTicks: priceForLevel(order.levelIndex, side, cbook, prices),
987
+ quantityInLots: order.quantityInLots,
988
+ orderId: order.orderId,
989
+ orderEntryIndex: order.orderEntryIndex,
990
+ seatIndex: order.seatIndex,
991
+ clientId: order.clientId,
992
+ expirationTime: order.expirationTime,
993
+ };
994
+ }
995
+
996
+ function groupByPrice(orders: ClobOrderBookOrder[], side: ClobOrderSide): ClobOrderBookLevel[] {
997
+ const levels = new Map<bigint, ClobOrderBookLevel>();
998
+ for (const order of orders) {
999
+ if (order.quantityInLots === 0n) continue;
1000
+ const existing = levels.get(order.priceInTicks);
1001
+ if (existing) {
1002
+ existing.quantityInLots += order.quantityInLots;
1003
+ existing.orders.push(order);
1004
+ } else {
1005
+ levels.set(order.priceInTicks, {
1006
+ side,
1007
+ priceInTicks: order.priceInTicks,
1008
+ quantityInLots: order.quantityInLots,
1009
+ orders: [order],
1010
+ });
1011
+ }
1012
+ }
1013
+ return [...levels.values()].sort((a, b) => {
1014
+ if (a.priceInTicks === b.priceInTicks) return 0;
1015
+ const asc = a.priceInTicks < b.priceInTicks ? -1 : 1;
1016
+ return side === 'buy' ? -asc : asc;
1017
+ });
1018
+ }
1019
+
1020
+ function priceForLevel(
1021
+ levelIndex: number,
1022
+ side: ClobOrderSide,
1023
+ cbook?: ClobCbook,
1024
+ prices?: Map<number, bigint> | Record<number, bigint>
1025
+ ): bigint {
1026
+ if (cbook) return priceForCbookLevel(levelIndex, side, cbook);
1027
+ const mappedPrice = priceFromMap(levelIndex, prices);
1028
+ if (mappedPrice !== undefined) return mappedPrice;
1029
+ throw new Error('Missing CLOB ' + side + ' price for cbook level ' + levelIndex);
1030
+ }
1031
+
1032
+ function priceFromMap(
1033
+ levelIndex: number,
1034
+ prices?: Map<number, bigint> | Record<number, bigint>
1035
+ ): bigint | undefined {
1036
+ if (!prices) return undefined;
1037
+ return prices instanceof Map ? prices.get(levelIndex) : prices[levelIndex];
1038
+ }
1039
+
1040
+ function priceForCbookLevel(levelIndex: number, side: ClobOrderSide, cbook: ClobCbook): bigint {
1041
+ const levelCount = cbook.levels.length;
1042
+ if (levelCount === 0) throw new Error('Cannot derive CLOB ' + side + ' price from an empty cbook');
1043
+ if (!Number.isInteger(levelIndex) || levelIndex < 0 || levelIndex >= levelCount) {
1044
+ throw new Error('CLOB ' + side + ' level index ' + levelIndex + ' is outside cbook level count ' + levelCount);
1045
+ }
1046
+ if (cbook.bestPriceInTicks === CLOB_CBOOK_EMPTY_PRICE_IN_TICKS) {
1047
+ throw new Error('Cannot derive CLOB ' + side + ' price from an empty cbook');
1048
+ }
1049
+
1050
+ const distance = levelIndex >= cbook.bestLevelIndex
1051
+ ? levelIndex - cbook.bestLevelIndex
1052
+ : levelCount - cbook.bestLevelIndex + levelIndex;
1053
+ const cbookPriceInTicks = cbook.bestPriceInTicks + BigInt(distance);
1054
+ return side === 'buy' ? CLOB_CBOOK_MAX_PRICE_IN_TICKS - cbookPriceInTicks : cbookPriceInTicks;
1055
+ }
1056
+
1057
+ function accountData(accountOrData: Account | Uint8Array, label: string): Uint8Array {
1058
+ const data = accountOrData instanceof Uint8Array ? accountOrData : accountOrData.data?.data;
1059
+ if (!data) throw new Error(`${label} data is missing`);
1060
+ return data;
1061
+ }
1062
+
1063
+ function optionalAccountIndex(context: AccountLookupContext, pubkey?: Uint8Array): number {
1064
+ return pubkey ? accountIndex(context, pubkey) : 0xffff;
1065
+ }
1066
+
1067
+ function accountIndex(context: AccountLookupContext, pubkey: Uint8Array): number {
1068
+ const index = context.getAccountIndex(pubkey);
1069
+ return assertU16(index, 'account index');
1070
+ }
1071
+
1072
+ function assertU8(value: number, label: string): number {
1073
+ if (!Number.isInteger(value) || value < 0 || value > 0xff) {
1074
+ throw new Error(`${label} must be an integer between 0 and 255`);
1075
+ }
1076
+ return value;
1077
+ }
1078
+
1079
+ function assertU16(value: number, label: string): number {
1080
+ if (!Number.isInteger(value) || value < 0 || value > 0xffff) {
1081
+ throw new Error(`${label} must be an integer between 0 and 65535`);
1082
+ }
1083
+ return value;
1084
+ }
1085
+
1086
+ function assertU64(value: bigint, label: string): void {
1087
+ if (value < 0n || value > 0xffffffffffffffffn) {
1088
+ throw new Error(`${label} must be between 0 and 18446744073709551615`);
1089
+ }
1090
+ }
1091
+
1092
+ function assertClientId(value: Uint8Array): Uint8Array {
1093
+ if (value.length !== CLOB_CLIENT_ID_SIZE) {
1094
+ throw new Error(`clientId must be ${CLOB_CLIENT_ID_SIZE} bytes`);
1095
+ }
1096
+ return value;
1097
+ }
1098
+
1099
+ function bitField(value: bigint, begin: bigint, end: bigint): number {
1100
+ const mask = (1n << (end - begin)) - 1n;
1101
+ return Number((value >> begin) & mask);
1102
+ }
1103
+
1104
+ function eventSideFromValue(value: number): ClobOrderSide {
1105
+ if (value === CLOB_EVENT_SIDE_BUY) return 'buy';
1106
+ if (value === CLOB_EVENT_SIDE_SELL) return 'sell';
1107
+ throw new Error(`unknown CLOB event side: ${value}`);
1108
+ }
1109
+
1110
+ function tokenSideFromValue(value: number): ClobTokenSide {
1111
+ if (value === CLOB_EVENT_TOKEN_SIDE_BASE) return 'base';
1112
+ if (value === CLOB_EVENT_TOKEN_SIDE_QUOTE) return 'quote';
1113
+ throw new Error(`unknown CLOB token side: ${value}`);
1114
+ }
1115
+
1116
+ function removalReasonFromValue(value: number): ClobOrderRemovalReason {
1117
+ switch (value) {
1118
+ case CLOB_EVENT_REMOVE_REASON_FILLED: return 'filled';
1119
+ case CLOB_EVENT_REMOVE_REASON_EXPIRED: return 'expired';
1120
+ case CLOB_EVENT_REMOVE_REASON_EVICTED: return 'evicted';
1121
+ case CLOB_EVENT_REMOVE_REASON_USER: return 'user';
1122
+ default: throw new Error(`unknown CLOB removal reason: ${value}`);
1123
+ }
1124
+ }
1125
+
1126
+ function orderTypeFromValue(value: number): ClobOrderType {
1127
+ switch (value) {
1128
+ case CLOB_ORDER_TYPE_GTC: return 'gtc';
1129
+ case CLOB_ORDER_TYPE_MTL: return 'mtl';
1130
+ case CLOB_ORDER_TYPE_ALO: return 'alo';
1131
+ case CLOB_ORDER_TYPE_IOC: return 'ioc';
1132
+ case CLOB_ORDER_TYPE_FOK: return 'fok';
1133
+ default: throw new Error(`unknown CLOB order type: ${value}`);
1134
+ }
1135
+ }
1136
+
1137
+ function pubkeyViewToAddress(pubkey: unknown): string {
1138
+ return encodeAddress(bytesFromView(pubkey));
1139
+ }
1140
+
1141
+ function bytesFromView(value: unknown): Uint8Array {
1142
+ const buffer = (value as { buffer?: Uint8Array }).buffer;
1143
+ if (buffer instanceof Uint8Array) return new Uint8Array(buffer);
1144
+ if (value instanceof Pubkey) return value.toBytes();
1145
+ throw new Error('generated view did not expose a byte buffer');
1146
+ }