@thru/programs 0.3.4 → 0.3.6

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.
Files changed (152) hide show
  1. package/README.md +124 -39
  2. package/dist/abi-manager/index.cjs +9568 -0
  3. package/dist/abi-manager/index.cjs.map +1 -0
  4. package/dist/abi-manager/index.d.cts +2169 -0
  5. package/dist/abi-manager/index.d.ts +2169 -0
  6. package/dist/abi-manager/index.js +4 -0
  7. package/dist/abi-manager/index.js.map +1 -0
  8. package/dist/amm/index.cjs +132 -33
  9. package/dist/amm/index.cjs.map +1 -1
  10. package/dist/amm/index.d.cts +1 -1
  11. package/dist/amm/index.d.ts +1 -1
  12. package/dist/amm/index.js +5 -2
  13. package/dist/amm/index.js.map +1 -1
  14. package/dist/bootstrap-addresses/index.cjs +118 -0
  15. package/dist/bootstrap-addresses/index.cjs.map +1 -0
  16. package/dist/bootstrap-addresses/index.d.cts +44 -0
  17. package/dist/bootstrap-addresses/index.d.ts +44 -0
  18. package/dist/bootstrap-addresses/index.js +5 -0
  19. package/dist/bootstrap-addresses/index.js.map +1 -0
  20. package/dist/chunk-6IC6CO5S.js +9443 -0
  21. package/dist/chunk-6IC6CO5S.js.map +1 -0
  22. package/dist/chunk-7DHFYBRW.js +51 -0
  23. package/dist/chunk-7DHFYBRW.js.map +1 -0
  24. package/dist/chunk-7FBCBZIY.js +41 -0
  25. package/dist/chunk-7FBCBZIY.js.map +1 -0
  26. package/dist/chunk-BNYDH4ZP.js +4351 -0
  27. package/dist/chunk-BNYDH4ZP.js.map +1 -0
  28. package/dist/{chunk-J7B7XYOI.js → chunk-CYG4PB65.js} +14 -41
  29. package/dist/chunk-CYG4PB65.js.map +1 -0
  30. package/dist/chunk-VNTPD4AR.js +37 -0
  31. package/dist/chunk-VNTPD4AR.js.map +1 -0
  32. package/dist/chunk-YX7BLFQZ.js +81 -0
  33. package/dist/chunk-YX7BLFQZ.js.map +1 -0
  34. package/dist/chunk-ZHF2PH5H.js +6536 -0
  35. package/dist/chunk-ZHF2PH5H.js.map +1 -0
  36. package/dist/clob/index.cjs +8461 -4922
  37. package/dist/clob/index.cjs.map +1 -1
  38. package/dist/clob/index.d.cts +1115 -53
  39. package/dist/clob/index.d.ts +1115 -53
  40. package/dist/clob/index.js +6817 -3395
  41. package/dist/clob/index.js.map +1 -1
  42. package/dist/deploy/index.cjs +24751 -0
  43. package/dist/deploy/index.cjs.map +1 -0
  44. package/dist/deploy/index.d.cts +180 -0
  45. package/dist/deploy/index.d.ts +180 -0
  46. package/dist/deploy/index.js +1849 -0
  47. package/dist/deploy/index.js.map +1 -0
  48. package/dist/helpers-DD7q61nr.d.cts +7 -0
  49. package/dist/helpers-DD7q61nr.d.ts +7 -0
  50. package/dist/manager/index.cjs +6680 -0
  51. package/dist/manager/index.cjs.map +1 -0
  52. package/dist/manager/index.d.cts +1279 -0
  53. package/dist/manager/index.d.ts +1279 -0
  54. package/dist/manager/index.js +5 -0
  55. package/dist/manager/index.js.map +1 -0
  56. package/dist/multicall/index.cjs +117 -40
  57. package/dist/multicall/index.cjs.map +1 -1
  58. package/dist/multicall/index.d.cts +5 -2
  59. package/dist/multicall/index.d.ts +5 -2
  60. package/dist/multicall/index.js +4 -1
  61. package/dist/oracle/index.cjs +122 -14
  62. package/dist/oracle/index.cjs.map +1 -1
  63. package/dist/oracle/index.d.cts +3 -1
  64. package/dist/oracle/index.d.ts +3 -1
  65. package/dist/oracle/index.js +7 -1
  66. package/dist/oracle/index.js.map +1 -1
  67. package/dist/passkey-manager/index.cjs +107 -6
  68. package/dist/passkey-manager/index.cjs.map +1 -1
  69. package/dist/passkey-manager/index.d.cts +1 -1
  70. package/dist/passkey-manager/index.d.ts +1 -1
  71. package/dist/passkey-manager/index.js +6 -3
  72. package/dist/passkey-manager/index.js.map +1 -1
  73. package/dist/uploader/index.cjs +4442 -0
  74. package/dist/uploader/index.cjs.map +1 -0
  75. package/dist/uploader/index.d.cts +761 -0
  76. package/dist/uploader/index.d.ts +761 -0
  77. package/dist/uploader/index.js +4 -0
  78. package/dist/uploader/index.js.map +1 -0
  79. package/package.json +27 -2
  80. package/src/abi-manager/abi/thru/blockchain/state_proof/types.ts +1906 -0
  81. package/src/abi-manager/abi/thru/common/primitives/types.ts +2428 -0
  82. package/src/abi-manager/abi/thru/program/abi_manager/types.ts +7037 -0
  83. package/src/abi-manager/accounts.ts +91 -0
  84. package/src/abi-manager/constants.ts +19 -0
  85. package/src/abi-manager/derivation.ts +86 -0
  86. package/src/abi-manager/errors.ts +48 -0
  87. package/src/abi-manager/index.test.ts +136 -0
  88. package/src/abi-manager/index.ts +56 -0
  89. package/src/abi-manager/instructions.ts +573 -0
  90. package/src/abi-manager/types.ts +150 -0
  91. package/src/amm/index.test.ts +2 -6
  92. package/src/amm/index.ts +2 -2
  93. package/src/bootstrap-addresses/index.test.ts +59 -0
  94. package/src/bootstrap-addresses/index.ts +58 -0
  95. package/src/clob/abi/thru/program/clob/types.ts +6981 -3070
  96. package/src/clob/exchange-client.test.ts +115 -2
  97. package/src/clob/exchange-client.ts +52 -13
  98. package/src/clob/exchange.test.ts +18 -16
  99. package/src/clob/exchange.ts +4 -0
  100. package/src/clob/index.test.ts +140 -7
  101. package/src/clob/index.ts +304 -12
  102. package/src/clob/price.test.ts +32 -0
  103. package/src/clob/price.ts +77 -0
  104. package/src/deploy/accounts.ts +208 -0
  105. package/src/deploy/chain.ts +163 -0
  106. package/src/deploy/constants.ts +30 -0
  107. package/src/deploy/deploy.test.ts +349 -0
  108. package/src/deploy/errors.ts +72 -0
  109. package/src/deploy/index.ts +44 -0
  110. package/src/deploy/inspection.ts +146 -0
  111. package/src/deploy/seeds.ts +29 -0
  112. package/src/deploy/types.ts +178 -0
  113. package/src/deploy/uploader.test.ts +326 -0
  114. package/src/deploy/uploader.ts +558 -0
  115. package/src/deploy/validation-imports.test.ts +55 -0
  116. package/src/deploy/validation.ts +183 -0
  117. package/src/deploy/workflows.test.ts +422 -0
  118. package/src/deploy/workflows.ts +1088 -0
  119. package/src/helpers/bytes.test.ts +58 -0
  120. package/src/helpers/bytes.ts +28 -3
  121. package/src/manager/abi/thru/blockchain/state_proof/types.ts +1906 -0
  122. package/src/manager/abi/thru/common/primitives/types.ts +2428 -0
  123. package/src/manager/abi/thru/program/manager/types.ts +3814 -0
  124. package/src/manager/accounts.ts +44 -0
  125. package/src/manager/constants.ts +16 -0
  126. package/src/manager/derivation.ts +32 -0
  127. package/src/manager/errors.ts +47 -0
  128. package/src/manager/index.test.ts +108 -0
  129. package/src/manager/index.ts +68 -0
  130. package/src/manager/instructions.ts +281 -0
  131. package/src/manager/types.ts +95 -0
  132. package/src/manager/validation.ts +35 -0
  133. package/src/multicall/index.test.ts +11 -2
  134. package/src/multicall/index.ts +12 -5
  135. package/src/oracle/index.ts +4 -0
  136. package/src/passkey-manager/constants.ts +2 -1
  137. package/src/passkey-manager/validate.test.ts +2 -2
  138. package/src/uploader/abi/thru/common/primitives/types.ts +2428 -0
  139. package/src/uploader/abi/thru/program/uploader/types.ts +3022 -0
  140. package/src/uploader/accounts.ts +38 -0
  141. package/src/uploader/constants.ts +14 -0
  142. package/src/uploader/derivation.ts +34 -0
  143. package/src/uploader/errors.ts +25 -0
  144. package/src/uploader/index.test.ts +107 -0
  145. package/src/uploader/index.ts +34 -0
  146. package/src/uploader/instructions.ts +163 -0
  147. package/src/uploader/types.ts +67 -0
  148. package/src/utils/helpers.ts +121 -0
  149. package/tsup.config.ts +5 -0
  150. package/dist/chunk-J7B7XYOI.js.map +0 -1
  151. package/dist/chunk-P5OABVJI.js +0 -28
  152. package/dist/chunk-P5OABVJI.js.map +0 -1
package/src/clob/index.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { Pubkey } from '@thru/sdk';
1
+ import { Pubkey, deriveProgramAddress } from '@thru/sdk';
2
2
  import { encodeAddress } from '@thru/sdk/helpers';
3
3
  import type { Account } from '@thru/sdk';
4
+ import { BOOTSTRAP_PROGRAM_ADDRESSES } from '../bootstrap-addresses';
4
5
  import {
5
6
  ArenaHeader,
6
7
  CbookAccount,
@@ -8,13 +9,18 @@ import {
8
9
  CbookLevel,
9
10
  ClobEvent,
10
11
  ClobInstructionBuilder,
11
- ClobProgramAccount,
12
12
  CreateOrderEntryInstructionBuilder,
13
13
  CreateSeatlessOrderEntryInstructionBuilder,
14
+ ExchangeInitializeInstructionBuilder,
15
+ ExchangeRecoverAdminInstructionBuilder,
16
+ ExchangeSetAdminInstructionBuilder,
17
+ ExchangeSetStatusInstructionBuilder,
18
+ ExchangeMetaAccount,
14
19
  MarketAccount as MarketAccountView,
15
20
  MarketCreateInstructionBuilder,
16
21
  MarketRecordInstructionBuilder,
17
22
  MarketSetStatusInstructionBuilder,
23
+ MarketSetExchangeStatusInstructionBuilder,
18
24
  ModifyOrderEntryInstructionBuilder,
19
25
  OrderArenaAccount,
20
26
  OrderEntry as OrderEntryView,
@@ -45,6 +51,22 @@ export {
45
51
  CreateOrderEntryInstructionBuilder,
46
52
  CreateSeatlessOrderEntryInstruction,
47
53
  CreateSeatlessOrderEntryInstructionBuilder,
54
+ ExchangeInitializeInstruction,
55
+ ExchangeInitializeInstructionBuilder,
56
+ ExchangeRecoverAdminInstruction,
57
+ ExchangeRecoverAdminInstructionBuilder,
58
+ ExchangeSetAdminInstruction,
59
+ ExchangeSetAdminInstructionBuilder,
60
+ ExchangeSetStatusInstruction,
61
+ ExchangeSetStatusInstructionBuilder,
62
+ ExchangeAdminEvent,
63
+ ExchangeAdminEventBuilder,
64
+ ExchangeInitializedEvent,
65
+ ExchangeInitializedEventBuilder,
66
+ ExchangeStatusEvent,
67
+ ExchangeStatusEventBuilder,
68
+ ExchangeMetaAccount,
69
+ ExchangeMetaAccountBuilder,
48
70
  MarketAccount as MarketAccountView,
49
71
  MarketAccountBuilder,
50
72
  MarketCreateInstruction,
@@ -55,6 +77,10 @@ export {
55
77
  MarketRecordInstructionBuilder,
56
78
  MarketSetStatusInstruction,
57
79
  MarketSetStatusInstructionBuilder,
80
+ MarketSetExchangeStatusInstruction,
81
+ MarketSetExchangeStatusInstructionBuilder,
82
+ MarketExchangeStatusEvent,
83
+ MarketExchangeStatusEventBuilder,
58
84
  ModifyOrderEntryInstruction,
59
85
  ModifyOrderEntryInstructionBuilder,
60
86
  OrderArenaAccount,
@@ -92,6 +118,11 @@ export const CLOB_INSTRUCTION_MODIFY_ORDER_ENTRY = 5;
92
118
  export const CLOB_INSTRUCTION_MARKET_SET_STATUS = 8;
93
119
  export const CLOB_INSTRUCTION_MARKET_CREATE = 9;
94
120
  export const CLOB_INSTRUCTION_CREATE_SEATLESS_ORDER_ENTRY = 10;
121
+ export const CLOB_INSTRUCTION_EXCHANGE_INITIALIZE = 11;
122
+ export const CLOB_INSTRUCTION_EXCHANGE_SET_STATUS = 12;
123
+ export const CLOB_INSTRUCTION_EXCHANGE_SET_ADMIN = 13;
124
+ export const CLOB_INSTRUCTION_EXCHANGE_RECOVER_ADMIN = 14;
125
+ export const CLOB_INSTRUCTION_MARKET_SET_EXCHANGE_STATUS = 15;
95
126
 
96
127
  export const CLOB_EVENT_SEAT_ASSIGNED = 1;
97
128
  export const CLOB_EVENT_ORDER_CANCELLED = 2;
@@ -103,6 +134,10 @@ export const CLOB_EVENT_ORDER_MODIFIED = 7;
103
134
  export const CLOB_EVENT_TOKEN_DEPOSIT = 8;
104
135
  export const CLOB_EVENT_TOKEN_WITHDRAW = 9;
105
136
  export const CLOB_EVENT_MARKET_STATUS = 10;
137
+ export const CLOB_EVENT_EXCHANGE_INITIALIZED = 11;
138
+ export const CLOB_EVENT_EXCHANGE_STATUS = 12;
139
+ export const CLOB_EVENT_EXCHANGE_ADMIN = 13;
140
+ export const CLOB_EVENT_MARKET_EXCHANGE_STATUS = 14;
106
141
 
107
142
  export const CLOB_EVENT_SIDE_BUY = 0;
108
143
  export const CLOB_EVENT_SIDE_SELL = 1;
@@ -117,9 +152,13 @@ export const CLOB_STATUS_FLAG_PAUSED = 1 << 0;
117
152
  export const CLOB_STATUS_FLAG_POST_ONLY = 1 << 1;
118
153
  export const CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN = 1 << 2;
119
154
  export const CLOB_STATUS_FLAG_DEPOSITS_FROZEN = 1 << 3;
155
+ export const CLOB_STATUS_FLAG_MASK =
156
+ CLOB_STATUS_FLAG_PAUSED |
157
+ CLOB_STATUS_FLAG_POST_ONLY |
158
+ CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN |
159
+ CLOB_STATUS_FLAG_DEPOSITS_FROZEN;
120
160
 
121
- export const CLOB_PROGRAM_ADDRESS =
122
- 'tamjQOFxFORIZhqbJjN83oAkRmSbKhLmULpvSHblK4GGIg';
161
+ export const CLOB_PROGRAM_ADDRESS = BOOTSTRAP_PROGRAM_ADDRESSES.clob;
123
162
 
124
163
  export const CLOB_ORDER_TYPE_GTC = 0;
125
164
  export const CLOB_ORDER_TYPE_MTL = 1;
@@ -133,8 +172,15 @@ export const CLOB_MODIFY_FLAG_FAIL_IF_OUT_OF_RANGE = 1 << 0;
133
172
  export const CLOB_MODIFY_FLAG_HAS_CLIENT_ID = 1 << 1;
134
173
  export const CLOB_MODIFY_FLAG_HAS_ORDER_ID = 1 << 2;
135
174
 
136
- export const CLOB_MARKET_ACCOUNT_SIZE = 256;
175
+ export const CLOB_MARKET_MAGIC = 0x77;
176
+ export const CLOB_MARKET_ACCOUNT_SIZE = 224;
177
+ export const CLOB_SEAT_MANAGER_RESERVED_SIZE = 256;
178
+ export const CLOB_EXCHANGE_META_ACCOUNT_SIZE = 96;
179
+ export const CLOB_EXCHANGE_META_MAGIC = 0xF17EDA2CC10B0078n;
180
+ export const CLOB_EXCHANGE_META_VERSION = 1;
181
+ export const CLOB_EXCHANGE_META_SEED = fixedSeed('exchange_meta');
137
182
  export const CLOB_ARENA_HEADER_SIZE = 64;
183
+ export const CLOB_SEAT_ARENA_ENTRIES_OFFSET = CLOB_SEAT_MANAGER_RESERVED_SIZE + CLOB_ARENA_HEADER_SIZE;
138
184
  export const CLOB_ORDER_ENTRY_SIZE = 64;
139
185
  export const CLOB_SEAT_ENTRY_SIZE = 64;
140
186
  export const CLOB_CBOOK_HEADER_SIZE = 16;
@@ -155,7 +201,12 @@ type ClobInstructionVariant =
155
201
  | 'modify_order_entry'
156
202
  | 'market_set_status'
157
203
  | 'market_create'
158
- | 'create_seatless_order_entry';
204
+ | 'create_seatless_order_entry'
205
+ | 'exchange_initialize'
206
+ | 'exchange_set_status'
207
+ | 'exchange_set_admin'
208
+ | 'exchange_recover_admin'
209
+ | 'market_set_exchange_status';
159
210
 
160
211
  export type ClobOrderSide = 'buy' | 'sell';
161
212
  export type ClobOrderType = 'gtc' | 'mtl' | 'alo' | 'ioc' | 'fok';
@@ -174,6 +225,7 @@ export interface MarketRecordArgs {
174
225
  asksCbookAccountBytes: Uint8Array;
175
226
  seatAuthorityAccountBytes?: Uint8Array;
176
227
  seatIndex?: number;
228
+ exchangeMetaAccountBytes: Uint8Array;
177
229
  tokenProgramAccountBytes: Uint8Array;
178
230
  baseVaultAccountBytes: Uint8Array;
179
231
  quoteVaultAccountBytes: Uint8Array;
@@ -194,6 +246,35 @@ export interface MarketCreateArgs extends MarketRecordArgs {
194
246
  quoteVaultStateProof: Uint8Array;
195
247
  }
196
248
 
249
+ export interface ExchangeInitializeArgs {
250
+ exchangeMetaAccountBytes: Uint8Array;
251
+ programMetaAccountBytes: Uint8Array;
252
+ authorityAccountBytes: Uint8Array;
253
+ tokenProgramAccountBytes: Uint8Array;
254
+ exchangeAdminAccountBytes: Uint8Array;
255
+ stateProof: Uint8Array;
256
+ }
257
+
258
+ export interface ExchangeSetStatusArgs {
259
+ exchangeMetaAccountBytes: Uint8Array;
260
+ exchangeAdminAccountBytes: Uint8Array;
261
+ statusFlags: number;
262
+ }
263
+
264
+ export interface ExchangeSetAdminArgs {
265
+ exchangeMetaAccountBytes: Uint8Array;
266
+ authorityAccountBytes: Uint8Array;
267
+ newAdminAccountBytes: Uint8Array;
268
+ }
269
+
270
+ export interface ExchangeRecoverAdminArgs extends ExchangeSetAdminArgs {
271
+ programMetaAccountBytes: Uint8Array;
272
+ }
273
+
274
+ export interface MarketSetExchangeStatusArgs extends MarketSetStatusArgs {
275
+ exchangeAdminAccountBytes: Uint8Array;
276
+ }
277
+
197
278
  export interface SeatCreateArgs {
198
279
  marketRecordIndex: number;
199
280
  seatAuthorityAccountBytes: Uint8Array;
@@ -248,18 +329,26 @@ export interface MarketSetStatusArgs {
248
329
  export interface ClobMarket {
249
330
  magic: number;
250
331
  statusFlags: number;
332
+ exchangeStatusFlags: number;
251
333
  lotSize: bigint;
252
334
  tickSize: bigint;
253
335
  nextOrderId: bigint;
254
336
  orderEntry: string;
255
337
  bidsCbook: string;
256
338
  asksCbook: string;
257
- tokenProgram: string;
258
339
  baseVault: string;
259
340
  quoteVault: string;
260
341
  marketAuthority: string;
261
342
  }
262
343
 
344
+ export interface ClobExchangeMeta {
345
+ magic: bigint;
346
+ version: number;
347
+ statusFlags: number;
348
+ tokenProgram: string;
349
+ exchangeAdmin: string;
350
+ }
351
+
263
352
  export interface ClobArenaHeader {
264
353
  nextEntryIndex: number;
265
354
  freeMagic: bigint;
@@ -439,8 +528,96 @@ export type ParsedClobEvent =
439
528
  statusFlags: number;
440
529
  market: string;
441
530
  marketAuthority: string;
531
+ })
532
+ | (ParsedClobEventBase & {
533
+ variant: 'exchange_initialized';
534
+ statusFlags: number;
535
+ exchangeMeta: string;
536
+ tokenProgram: string;
537
+ exchangeAdmin: string;
538
+ })
539
+ | (ParsedClobEventBase & {
540
+ variant: 'exchange_status';
541
+ oldStatusFlags: number;
542
+ newStatusFlags: number;
543
+ exchangeMeta: string;
544
+ exchangeAdmin: string;
545
+ })
546
+ | (ParsedClobEventBase & {
547
+ variant: 'exchange_admin';
548
+ isRecovery: boolean;
549
+ exchangeMeta: string;
550
+ oldAdmin: string;
551
+ newAdmin: string;
552
+ authority: string;
553
+ })
554
+ | (ParsedClobEventBase & {
555
+ variant: 'market_exchange_status';
556
+ statusFlags: number;
557
+ market: string;
558
+ exchangeAdmin: string;
442
559
  });
443
560
 
561
+ export function deriveClobExchangeMetaAddress(clobProgramAddress: string | Uint8Array | Pubkey) {
562
+ return deriveProgramAddress({
563
+ programAddress: clobProgramAddress,
564
+ seed: CLOB_EXCHANGE_META_SEED,
565
+ ephemeral: false,
566
+ });
567
+ }
568
+
569
+ export function createExchangeInitializeInstruction(args: ExchangeInitializeArgs): InstructionData {
570
+ return async (context) => {
571
+ const builder = new ExchangeInitializeInstructionBuilder()
572
+ .set_reserved0(0)
573
+ .set_exchange_meta_account_idx(accountIndex(context, args.exchangeMetaAccountBytes))
574
+ .set_program_meta_account_idx(accountIndex(context, args.programMetaAccountBytes))
575
+ .set_authority_account_idx(accountIndex(context, args.authorityAccountBytes))
576
+ .set_token_program_idx(accountIndex(context, args.tokenProgramAccountBytes))
577
+ .set_exchange_admin_account_idx(accountIndex(context, args.exchangeAdminAccountBytes));
578
+ builder.proof().write(args.stateProof).finish();
579
+ return buildClobInstruction('exchange_initialize', builder.build());
580
+ };
581
+ }
582
+
583
+ export function createExchangeSetStatusInstruction(args: ExchangeSetStatusArgs): InstructionData {
584
+ return async (context) => {
585
+ const payload = new ExchangeSetStatusInstructionBuilder()
586
+ .set_status_flags(assertStatusFlags(args.statusFlags))
587
+ .set_exchange_meta_account_idx(accountIndex(context, args.exchangeMetaAccountBytes))
588
+ .set_exchange_admin_account_idx(accountIndex(context, args.exchangeAdminAccountBytes))
589
+ .set_reserved0(0)
590
+ .build();
591
+ return buildClobInstruction('exchange_set_status', payload);
592
+ };
593
+ }
594
+
595
+ export function createExchangeSetAdminInstruction(args: ExchangeSetAdminArgs): InstructionData {
596
+ return async (context) => {
597
+ const payload = new ExchangeSetAdminInstructionBuilder()
598
+ .set_reserved0(0)
599
+ .set_exchange_meta_account_idx(accountIndex(context, args.exchangeMetaAccountBytes))
600
+ .set_authority_account_idx(accountIndex(context, args.authorityAccountBytes))
601
+ .set_new_admin_account_idx(accountIndex(context, args.newAdminAccountBytes))
602
+ .build();
603
+ return buildClobInstruction('exchange_set_admin', payload);
604
+ };
605
+ }
606
+
607
+ export function createExchangeRecoverAdminInstruction(args: ExchangeRecoverAdminArgs): InstructionData {
608
+ return async (context) => {
609
+ const payload = new ExchangeRecoverAdminInstructionBuilder()
610
+ .set_reserved0(0)
611
+ .set_exchange_meta_account_idx(accountIndex(context, args.exchangeMetaAccountBytes))
612
+ .set_program_meta_account_idx(accountIndex(context, args.programMetaAccountBytes))
613
+ .set_authority_account_idx(accountIndex(context, args.authorityAccountBytes))
614
+ .set_new_admin_account_idx(accountIndex(context, args.newAdminAccountBytes))
615
+ .set_reserved1([0, 0, 0, 0, 0, 0])
616
+ .build();
617
+ return buildClobInstruction('exchange_recover_admin', payload);
618
+ };
619
+ }
620
+
444
621
  export function createMarketRecordInstruction(args: MarketRecordArgs): InstructionData {
445
622
  const seatIndex = args.seatIndex === undefined
446
623
  ? CLOB_NULL_INDEX
@@ -454,10 +631,12 @@ export function createMarketRecordInstruction(args: MarketRecordArgs): Instructi
454
631
  .set_asks_cbook_account_idx(accountIndex(context, args.asksCbookAccountBytes))
455
632
  .set_seat_authority_account_idx(optionalAccountIndex(context, args.seatAuthorityAccountBytes))
456
633
  .set_seat_idx(seatIndex)
634
+ .set_exchange_meta_account_idx(accountIndex(context, args.exchangeMetaAccountBytes))
457
635
  .set_token_program_idx(accountIndex(context, args.tokenProgramAccountBytes))
458
636
  .set_base_vault_account_idx(accountIndex(context, args.baseVaultAccountBytes))
459
637
  .set_quote_vault_account_idx(accountIndex(context, args.quoteVaultAccountBytes))
460
638
  .set_market_authority_account_idx(optionalAccountIndex(context, args.marketAuthorityAccountBytes))
639
+ .set_reserved0([0, 0, 0, 0, 0, 0])
461
640
  .build();
462
641
  return buildClobInstruction('market_record', payload);
463
642
  };
@@ -473,6 +652,7 @@ export function createMarketCreateInstruction(args: MarketCreateArgs): Instructi
473
652
  .set_lot_size(args.lotSize)
474
653
  .set_tick_size(args.tickSize)
475
654
  .set_token_program_idx(accountIndex(context, args.tokenProgramAccountBytes))
655
+ .set_exchange_meta_account_idx(accountIndex(context, args.exchangeMetaAccountBytes))
476
656
  .set_base_mint_idx(accountIndex(context, args.baseMintAccountBytes))
477
657
  .set_quote_mint_idx(accountIndex(context, args.quoteMintAccountBytes))
478
658
  .set_seat_arena_account_idx(accountIndex(context, args.seatArenaAccountBytes))
@@ -481,7 +661,8 @@ export function createMarketCreateInstruction(args: MarketCreateArgs): Instructi
481
661
  .set_asks_cbook_account_idx(accountIndex(context, args.asksCbookAccountBytes))
482
662
  .set_base_vault_account_idx(accountIndex(context, args.baseVaultAccountBytes))
483
663
  .set_quote_vault_account_idx(accountIndex(context, args.quoteVaultAccountBytes))
484
- .set_market_authority_account_idx(accountIndex(context, args.marketAuthorityAccountBytes));
664
+ .set_market_authority_account_idx(optionalAccountIndex(context, args.marketAuthorityAccountBytes))
665
+ .set_reserved1([0, 0]);
485
666
  builder.proof_seat_arena().write(args.seatArenaStateProof).finish();
486
667
  builder.proof_order_arena().write(args.orderArenaStateProof).finish();
487
668
  builder.proof_bids_cbook().write(args.bidsCbookStateProof).finish();
@@ -570,18 +751,55 @@ export function createMarketSetStatusInstruction(args: MarketSetStatusArgs): Ins
570
751
  return async () => {
571
752
  const payload = new MarketSetStatusInstructionBuilder()
572
753
  .set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
573
- .set_status_flags(assertU8(args.statusFlags, 'statusFlags'))
754
+ .set_status_flags(assertStatusFlags(args.statusFlags))
574
755
  .set_reserved0([0, 0, 0, 0, 0])
575
756
  .build();
576
757
  return buildClobInstruction('market_set_status', payload);
577
758
  };
578
759
  }
579
760
 
761
+ export function createMarketSetExchangeStatusInstruction(args: MarketSetExchangeStatusArgs): InstructionData {
762
+ return async (context) => {
763
+ const payload = new MarketSetExchangeStatusInstructionBuilder()
764
+ .set_market_record_idx(assertU8(args.marketRecordIndex, 'marketRecordIndex'))
765
+ .set_status_flags(assertStatusFlags(args.statusFlags))
766
+ .set_reserved0(0)
767
+ .set_exchange_admin_account_idx(accountIndex(context, args.exchangeAdminAccountBytes))
768
+ .set_reserved1(0)
769
+ .build();
770
+ return buildClobInstruction('market_set_exchange_status', payload);
771
+ };
772
+ }
773
+
774
+ export function parseExchangeMetaAccount(accountOrData: Account | Uint8Array): ClobExchangeMeta {
775
+ const data = accountData(accountOrData, 'CLOB exchange metadata account');
776
+ if (data.length !== CLOB_EXCHANGE_META_ACCOUNT_SIZE) {
777
+ throw new Error("CLOB exchange metadata account must be " + CLOB_EXCHANGE_META_ACCOUNT_SIZE + " bytes");
778
+ }
779
+ const parsed = ExchangeMetaAccount.from_array(data);
780
+ if (!parsed) throw new Error('CLOB exchange metadata account data is malformed');
781
+ if (parsed.get_magic() !== CLOB_EXCHANGE_META_MAGIC) {
782
+ throw new Error('CLOB exchange metadata account has an invalid magic value');
783
+ }
784
+ if (parsed.get_version() !== CLOB_EXCHANGE_META_VERSION) {
785
+ throw new Error('CLOB exchange metadata account has an unsupported version');
786
+ }
787
+ assertStatusFlags(parsed.get_status_flags());
788
+ return {
789
+ magic: parsed.get_magic(),
790
+ version: parsed.get_version(),
791
+ statusFlags: parsed.get_status_flags(),
792
+ tokenProgram: pubkeyViewToAddress(parsed.get_token_program_pubkey()),
793
+ exchangeAdmin: pubkeyViewToAddress(parsed.get_exchange_admin_pubkey()),
794
+ };
795
+ }
796
+
580
797
  export function parseClobProgramAccount(accountOrData: Account | Uint8Array): ClobMarket {
581
798
  const data = accountData(accountOrData, 'CLOB program account');
582
- const parsed = ClobProgramAccount.from_array(data);
799
+ if (data[0] !== CLOB_MARKET_MAGIC) throw new Error('CLOB program account is not a market account');
800
+ const parsed = MarketAccountView.from_array(data);
583
801
  if (!parsed) throw new Error('CLOB program account data is malformed');
584
- return marketFromView(parsed.get_market());
802
+ return marketFromView(parsed);
585
803
  }
586
804
 
587
805
  export function parseMarketAccount(accountOrData: Account | Uint8Array): ClobMarket {
@@ -833,6 +1051,54 @@ export function parseClobEvent(data: Uint8Array): ParsedClobEvent {
833
1051
  marketAuthority: pubkeyViewToAddress(event.get_market_authority()),
834
1052
  };
835
1053
  }
1054
+ case 'exchange_initialized': {
1055
+ const event = payload.asExchangeInitialized();
1056
+ if (!event) throw new Error('CLOB exchange_initialized event payload is malformed');
1057
+ return {
1058
+ ...base,
1059
+ variant: 'exchange_initialized',
1060
+ statusFlags: event.get_status_flags(),
1061
+ exchangeMeta: pubkeyViewToAddress(event.get_exchange_meta()),
1062
+ tokenProgram: pubkeyViewToAddress(event.get_token_program()),
1063
+ exchangeAdmin: pubkeyViewToAddress(event.get_exchange_admin()),
1064
+ };
1065
+ }
1066
+ case 'exchange_status': {
1067
+ const event = payload.asExchangeStatus();
1068
+ if (!event) throw new Error('CLOB exchange_status event payload is malformed');
1069
+ return {
1070
+ ...base,
1071
+ variant: 'exchange_status',
1072
+ oldStatusFlags: event.get_old_status_flags(),
1073
+ newStatusFlags: event.get_new_status_flags(),
1074
+ exchangeMeta: pubkeyViewToAddress(event.get_exchange_meta()),
1075
+ exchangeAdmin: pubkeyViewToAddress(event.get_exchange_admin()),
1076
+ };
1077
+ }
1078
+ case 'exchange_admin': {
1079
+ const event = payload.asExchangeAdmin();
1080
+ if (!event) throw new Error('CLOB exchange_admin event payload is malformed');
1081
+ return {
1082
+ ...base,
1083
+ variant: 'exchange_admin',
1084
+ isRecovery: event.get_is_recovery() !== 0,
1085
+ exchangeMeta: pubkeyViewToAddress(event.get_exchange_meta()),
1086
+ oldAdmin: pubkeyViewToAddress(event.get_old_admin()),
1087
+ newAdmin: pubkeyViewToAddress(event.get_new_admin()),
1088
+ authority: pubkeyViewToAddress(event.get_authority()),
1089
+ };
1090
+ }
1091
+ case 'market_exchange_status': {
1092
+ const event = payload.asMarketExchangeStatus();
1093
+ if (!event) throw new Error('CLOB market_exchange_status event payload is malformed');
1094
+ return {
1095
+ ...base,
1096
+ variant: 'market_exchange_status',
1097
+ statusFlags: event.get_status_flags(),
1098
+ market: pubkeyViewToAddress(event.get_market()),
1099
+ exchangeAdmin: pubkeyViewToAddress(event.get_exchange_admin()),
1100
+ };
1101
+ }
836
1102
  default:
837
1103
  throw new Error('CLOB event type is unsupported');
838
1104
  }
@@ -916,13 +1182,13 @@ function marketFromView(view: MarketAccountView): ClobMarket {
916
1182
  return {
917
1183
  magic: view.get_magic(),
918
1184
  statusFlags: view.get_status_flags(),
1185
+ exchangeStatusFlags: view.get_exchange_status_flags(),
919
1186
  lotSize: view.get_lot_size(),
920
1187
  tickSize: view.get_tick_size(),
921
1188
  nextOrderId: view.get_next_order_id(),
922
1189
  orderEntry: pubkeyViewToAddress(view.get_order_entry_pubkey()),
923
1190
  bidsCbook: pubkeyViewToAddress(view.get_bids_cbook_pubkey()),
924
1191
  asksCbook: pubkeyViewToAddress(view.get_asks_cbook_pubkey()),
925
- tokenProgram: pubkeyViewToAddress(view.get_token_program_pubkey()),
926
1192
  baseVault: pubkeyViewToAddress(view.get_base_vault_pubkey()),
927
1193
  quoteVault: pubkeyViewToAddress(view.get_quote_vault_pubkey()),
928
1194
  marketAuthority: pubkeyViewToAddress(view.get_market_authority_pubkey()),
@@ -1067,6 +1333,14 @@ function accountData(accountOrData: Account | Uint8Array, label: string): Uint8A
1067
1333
  return data;
1068
1334
  }
1069
1335
 
1336
+ function fixedSeed(value: string): Uint8Array {
1337
+ const bytes = new TextEncoder().encode(value);
1338
+ if (bytes.length > 32) throw new Error('seed cannot exceed 32 bytes');
1339
+ const seed = new Uint8Array(32);
1340
+ seed.set(bytes);
1341
+ return seed;
1342
+ }
1343
+
1070
1344
  function optionalAccountIndex(context: AccountLookupContext, pubkey?: Uint8Array): number {
1071
1345
  return pubkey ? accountIndex(context, pubkey) : 0xffff;
1072
1346
  }
@@ -1083,6 +1357,23 @@ function assertU8(value: number, label: string): number {
1083
1357
  return value;
1084
1358
  }
1085
1359
 
1360
+ function assertStatusFlags(value: number): number {
1361
+ const flags = assertU8(value, 'statusFlags');
1362
+ if ((flags & ~CLOB_STATUS_FLAG_MASK) !== 0) {
1363
+ throw new Error("statusFlags may only contain bits in mask 0x" + CLOB_STATUS_FLAG_MASK.toString(16));
1364
+ }
1365
+ return flags;
1366
+ }
1367
+
1368
+ export function effectiveClobStatusFlags(
1369
+ exchangeStatusFlags: number,
1370
+ market: Pick<ClobMarket, 'statusFlags' | 'exchangeStatusFlags'>
1371
+ ): number {
1372
+ return assertStatusFlags(exchangeStatusFlags) |
1373
+ assertStatusFlags(market.statusFlags) |
1374
+ assertStatusFlags(market.exchangeStatusFlags);
1375
+ }
1376
+
1086
1377
  function assertU16(value: number, label: string): number {
1087
1378
  if (!Number.isInteger(value) || value < 0 || value > 0xffff) {
1088
1379
  throw new Error(`${label} must be an integer between 0 and 65535`);
@@ -1161,3 +1452,4 @@ function bytesFromView(value: unknown): Uint8Array {
1161
1452
 
1162
1453
  export * from './exchange';
1163
1454
  export * from './exchange-client';
1455
+ export * from './price';
@@ -0,0 +1,32 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ clobMarketPriceNumber,
4
+ formatClobMarketPrice,
5
+ parseClobMarketPrice,
6
+ } from './price';
7
+
8
+ describe('CLOB market price units', () => {
9
+ const creditsPerWholeAsset = { baseDecimals: 0, quoteDecimals: 6 };
10
+
11
+ it('formats raw quote units as whole-token market prices', () => {
12
+ expect(formatClobMarketPrice(1_922_000_000n, creditsPerWholeAsset)).toBe('1922');
13
+ expect(formatClobMarketPrice(1_922_500_000n, creditsPerWholeAsset)).toBe('1922.5');
14
+ expect(clobMarketPriceNumber(1_922_000_000n, creditsPerWholeAsset)).toBe(1922);
15
+ });
16
+
17
+ it('parses displayed market prices into raw quote-per-base units', () => {
18
+ expect(parseClobMarketPrice('1922', creditsPerWholeAsset)).toBe(1_922_000_000n);
19
+ expect(parseClobMarketPrice('1922.5', creditsPerWholeAsset)).toBe(1_922_500_000n);
20
+ });
21
+
22
+ it('accounts for base decimals as well as quote decimals', () => {
23
+ const equalDecimals = { baseDecimals: 6, quoteDecimals: 6 };
24
+ expect(formatClobMarketPrice(1922n, equalDecimals)).toBe('1922');
25
+ expect(parseClobMarketPrice('1922', equalDecimals)).toBe(1922n);
26
+ });
27
+
28
+ it('rejects prices that cannot be represented exactly', () => {
29
+ expect(() => parseClobMarketPrice('1.0000001', creditsPerWholeAsset))
30
+ .toThrow('at most 6 decimal places');
31
+ });
32
+ });
@@ -0,0 +1,77 @@
1
+ const U64_MAX = (1n << 64n) - 1n;
2
+
3
+ export interface ClobMarketPriceUnits {
4
+ baseDecimals: number;
5
+ quoteDecimals: number;
6
+ }
7
+
8
+ /* A CLOB price is stored as raw quote units per raw base unit. Convert at
9
+ application boundaries so a price always reads as whole-token quote per
10
+ whole-token base. */
11
+ export function formatClobMarketPrice(
12
+ rawPrice: string | bigint,
13
+ units: ClobMarketPriceUnits,
14
+ ): string {
15
+ assertDecimals(units.baseDecimals);
16
+ assertDecimals(units.quoteDecimals);
17
+ const raw = typeof rawPrice === 'bigint' ? rawPrice : parseUnsigned(rawPrice, 'CLOB price');
18
+ const decimalShift = units.quoteDecimals - units.baseDecimals;
19
+ if (decimalShift <= 0) return (raw * 10n ** BigInt(-decimalShift)).toString();
20
+
21
+ const scale = 10n ** BigInt(decimalShift);
22
+ const whole = raw / scale;
23
+ const fraction = (raw % scale).toString().padStart(decimalShift, '0').replace(/0+$/, '');
24
+ return fraction ? `${whole}.${fraction}` : whole.toString();
25
+ }
26
+
27
+ export function parseClobMarketPrice(
28
+ displayPrice: string,
29
+ units: ClobMarketPriceUnits,
30
+ ): bigint {
31
+ assertDecimals(units.baseDecimals);
32
+ assertDecimals(units.quoteDecimals);
33
+ const trimmed = displayPrice.trim();
34
+ const match = /^(\d+)(?:\.(\d+))?$/.exec(trimmed);
35
+ if (!match) throw new Error('Price must be a positive number');
36
+
37
+ const decimalShift = units.quoteDecimals - units.baseDecimals;
38
+ const whole = BigInt(match[1]!);
39
+ const fraction = match[2] ?? '';
40
+ let raw: bigint;
41
+ if (decimalShift >= 0) {
42
+ if (fraction.length > decimalShift) {
43
+ throw new Error(`Price supports at most ${decimalShift} decimal places`);
44
+ }
45
+ raw = whole * 10n ** BigInt(decimalShift)
46
+ + BigInt(fraction.padEnd(decimalShift, '0') || '0');
47
+ } else {
48
+ if (fraction) throw new Error('Price must be a whole number');
49
+ const divisor = 10n ** BigInt(-decimalShift);
50
+ if (whole % divisor !== 0n) {
51
+ throw new Error(`Price must be a multiple of ${divisor}`);
52
+ }
53
+ raw = whole / divisor;
54
+ }
55
+
56
+ if (raw <= 0n) throw new Error('Price must be greater than zero');
57
+ if (raw > U64_MAX) throw new Error('Price exceeds the CLOB limit');
58
+ return raw;
59
+ }
60
+
61
+ export function clobMarketPriceNumber(
62
+ rawPrice: string | bigint,
63
+ units: ClobMarketPriceUnits,
64
+ ): number {
65
+ return Number(formatClobMarketPrice(rawPrice, units));
66
+ }
67
+
68
+ function parseUnsigned(value: string, label: string): bigint {
69
+ if (!/^\d+$/.test(value)) throw new Error(`${label} must be an unsigned integer`);
70
+ return BigInt(value);
71
+ }
72
+
73
+ function assertDecimals(decimals: number): void {
74
+ if (!Number.isSafeInteger(decimals) || decimals < 0) {
75
+ throw new Error('Token decimals are invalid');
76
+ }
77
+ }