@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
@@ -3,8 +3,17 @@ import { Pubkey } from '@thru/sdk';
3
3
  import { encodeAddress } from '@thru/sdk/helpers';
4
4
  import type { Thru } from '@thru/sdk/client';
5
5
  import { deriveTokenAccountAddress } from '../token';
6
- import { TokenAccountBuilder } from '../token/abi/thru/program/token/types';
7
- import { CLOB_STATUS_FLAG_DEPOSITS_FROZEN, SeatEntryBuilder } from './index';
6
+ import {
7
+ TickerFieldBuilder,
8
+ TokenAccountBuilder,
9
+ TokenMintAccountBuilder,
10
+ } from '../token/abi/thru/program/token/types';
11
+ import {
12
+ CLOB_PROGRAM_ADDRESS,
13
+ CLOB_STATUS_FLAG_DEPOSITS_FROZEN,
14
+ CLOB_STATUS_FLAG_PAUSED,
15
+ SeatEntryBuilder,
16
+ } from './index';
8
17
  import {
9
18
  ClobExchangeClientError,
10
19
  createClobExchangeClient,
@@ -14,6 +23,7 @@ import type { ClobAssetBalanceAllocation, ClobTradingMarket } from './exchange';
14
23
 
15
24
  const AUTHORITY = address(10);
16
25
  const TOKEN_PROGRAM = address(11);
26
+ const EXCHANGE_META = address(12);
17
27
  const BTC = address(20);
18
28
  const ETH = address(21);
19
29
  const USD = address(22);
@@ -29,11 +39,16 @@ describe('ClobExchangeClient', () => {
29
39
  balance(markets[1]!, USD, 'base', 60n),
30
40
  ],
31
41
  });
42
+ harness.setMint(USD, 6, 'USD');
32
43
 
33
44
  const snapshot = await harness.client.getAccountSnapshot({ authority: AUTHORITY });
34
45
 
35
46
  expect(snapshot.assets.map((asset) => asset.mint)).toEqual([BTC, ETH, USD].sort());
36
47
  expect(snapshot.assets.find((asset) => asset.mint === USD)?.exchange.freeAmount).toBe(100n);
48
+ expect(snapshot.assets.find((asset) => asset.mint === USD)).toMatchObject({
49
+ symbol: 'USD',
50
+ decimals: 6,
51
+ });
37
52
  expect(snapshot.unavailableMarkets).toEqual([]);
38
53
  for (const asset of snapshot.assets) {
39
54
  expect(asset.discoveryComplete).toBe(true);
@@ -164,6 +179,73 @@ describe('ClobExchangeClient', () => {
164
179
  expect(prepared.market.address).toBe(available.address);
165
180
  });
166
181
 
182
+ it('skips a paused existing market when an active market accepts deposits', async () => {
183
+ const paused = { ...market(44, BTC, USD), statusFlags: CLOB_STATUS_FLAG_PAUSED };
184
+ const active = market(45, BTC, USD);
185
+ const harness = createHarness({
186
+ markets: [paused, active],
187
+ allocations: [balance(paused, BTC, 'base', 25n)],
188
+ });
189
+ harness.setWalletBalance(BTC, 100n);
190
+ harness.setSeats(active, []);
191
+
192
+ const prepared = await harness.client.prepareDeposit({
193
+ authority: AUTHORITY,
194
+ mint: BTC,
195
+ amount: 10n,
196
+ });
197
+
198
+ expect(prepared.market.address).toBe(active.address);
199
+ });
200
+
201
+ it('rejects deposits when every compatible market is paused', async () => {
202
+ const paused = { ...market(46, BTC, USD), statusFlags: CLOB_STATUS_FLAG_PAUSED };
203
+ const harness = createHarness({ markets: [paused] });
204
+
205
+ await expect(harness.client.prepareDeposit({
206
+ authority: AUTHORITY,
207
+ mint: BTC,
208
+ amount: 10n,
209
+ })).rejects.toMatchObject({ code: 'market_paused' });
210
+ });
211
+
212
+ it('keeps paused markets available for withdrawals', async () => {
213
+ const paused = { ...market(48, BTC, USD), statusFlags: CLOB_STATUS_FLAG_PAUSED };
214
+ const harness = createHarness({
215
+ markets: [paused],
216
+ allocations: [balance(paused, BTC, 'base', 25n)],
217
+ });
218
+ harness.setSeats(paused, [{ authority: AUTHORITY, base: 25n, quote: 0n }]);
219
+
220
+ await expect(harness.client.prepareWithdrawal({
221
+ authority: AUTHORITY,
222
+ mint: BTC,
223
+ amount: 10n,
224
+ })).resolves.toMatchObject({ market: { address: paused.address } });
225
+ });
226
+
227
+ it('rejects a selected vault whose on-chain mint does not match', async () => {
228
+ const target = market(47, BTC, USD);
229
+ const harness = createHarness({ markets: [target] });
230
+ harness.setWalletBalance(BTC, 100n);
231
+ harness.setSeats(target, []);
232
+ harness.setVaultMint(target.baseVault, OTHER);
233
+
234
+ await expect(harness.client.prepareDeposit({
235
+ authority: AUTHORITY,
236
+ mint: BTC,
237
+ amount: 10n,
238
+ })).rejects.toMatchObject({
239
+ code: 'invalid_token_account',
240
+ details: {
241
+ market: target.address,
242
+ vault: target.baseVault,
243
+ expectedMint: BTC,
244
+ actualMint: OTHER,
245
+ },
246
+ });
247
+ });
248
+
167
249
  it('uses fresh seat balances for withdrawals and reports fragmented funds', async () => {
168
250
  const first = market(50, BTC, USD);
169
251
  const second = market(51, BTC, USD);
@@ -383,9 +465,27 @@ function createHarness({
383
465
  tokenProgramAddress: TOKEN_PROGRAM,
384
466
  });
385
467
 
468
+ for (const target of markets) {
469
+ accounts.set(target.baseVault, tokenAccount(target.baseMint, CLOB_PROGRAM_ADDRESS));
470
+ accounts.set(target.quoteVault, tokenAccount(target.quoteMint, CLOB_PROGRAM_ADDRESS));
471
+ }
472
+
386
473
  return {
387
474
  client,
388
475
  reads,
476
+ setMint(mint: string, decimals: number, symbol: string) {
477
+ const symbolBytes = new TextEncoder().encode(symbol);
478
+ const paddedSymbol = new Uint8Array(8);
479
+ paddedSymbol.set(symbolBytes);
480
+ const ticker = new TickerFieldBuilder()
481
+ .set_length(symbolBytes.length)
482
+ .set_bytes(Array.from(paddedSymbol))
483
+ .build();
484
+ accounts.set(mint, new TokenMintAccountBuilder()
485
+ .set_decimals(decimals)
486
+ .set_ticker(ticker)
487
+ .build());
488
+ },
389
489
  setWalletBalance(mint: string, amount: bigint, owner = AUTHORITY) {
390
490
  const tokenAccount = deriveTokenAccountAddress(
391
491
  thruClient,
@@ -400,6 +500,9 @@ function createHarness({
400
500
  .set_is_frozen(0)
401
501
  .build());
402
502
  },
503
+ setVaultMint(vault: string, mint: string) {
504
+ accounts.set(vault, tokenAccount(mint, CLOB_PROGRAM_ADDRESS));
505
+ },
403
506
  setSeats(target: ClobTradingMarket, seats: Array<{
404
507
  authority: string;
405
508
  base: bigint;
@@ -421,12 +524,22 @@ function createHarness({
421
524
  };
422
525
  }
423
526
 
527
+ function tokenAccount(mint: string, owner: string): Uint8Array {
528
+ return new TokenAccountBuilder()
529
+ .set_mint(bytesFor(mint))
530
+ .set_owner(bytesFor(owner))
531
+ .set_amount(0n)
532
+ .set_is_frozen(0)
533
+ .build();
534
+ }
535
+
424
536
  function market(id: number, baseMint: string, quoteMint: string): ClobTradingMarket {
425
537
  return {
426
538
  address: address(id),
427
539
  orderArena: address(id + 40),
428
540
  bidsCbook: address(id + 80),
429
541
  asksCbook: address(id + 120),
542
+ exchangeMeta: EXCHANGE_META,
430
543
  tokenProgram: TOKEN_PROGRAM,
431
544
  baseMint,
432
545
  quoteMint,
@@ -24,6 +24,7 @@ import {
24
24
  import {
25
25
  CLOB_PROGRAM_ADDRESS,
26
26
  CLOB_STATUS_FLAG_DEPOSITS_FROZEN,
27
+ CLOB_STATUS_FLAG_PAUSED,
27
28
  CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN,
28
29
  parseSeatArenaAccount,
29
30
  type ClobOrderSide,
@@ -63,6 +64,7 @@ export interface ClobExchangeAssetSnapshot {
63
64
  mint: string;
64
65
  tokenProgram: string;
65
66
  symbol: string | null;
67
+ decimals: number | null;
66
68
  discoveryComplete: boolean;
67
69
  exchange: {
68
70
  freeAmount: bigint;
@@ -121,6 +123,7 @@ export type ClobExchangeClientErrorCode =
121
123
  | 'insufficient_wallet_balance'
122
124
  | 'insufficient_exchange_balance'
123
125
  | 'fragmented_balance'
126
+ | 'market_paused'
124
127
  | 'invalid_token_account';
125
128
 
126
129
  export class ClobExchangeClientError extends Error {
@@ -227,14 +230,15 @@ export function createClobExchangeClient(
227
230
  const assets = uniqueSnapshotAssets(markets, allocations, authority);
228
231
  const snapshots = await Promise.all(assets.map(async ({ mint, tokenProgram }) => {
229
232
  const balance = balances.get(assetKey(mint, tokenProgram));
230
- const [wallet, symbol] = await Promise.all([
233
+ const [wallet, mintMetadata] = await Promise.all([
231
234
  readCanonicalWalletAccount(authority, mint, tokenProgram),
232
- readMintSymbol(mint),
235
+ readMintMetadata(mint),
233
236
  ]);
234
237
  return {
235
238
  mint,
236
239
  tokenProgram,
237
- symbol,
240
+ symbol: mintMetadata?.symbol ?? null,
241
+ decimals: mintMetadata?.decimals ?? null,
238
242
  discoveryComplete: isAssetDiscoveryComplete(
239
243
  unavailableMarkets,
240
244
  balance?.allocations ?? [],
@@ -298,28 +302,41 @@ export function createClobExchangeClient(
298
302
  );
299
303
  const eligible = marketsForAsset(markets, depositArgs.mint, args.tokenProgramAddress);
300
304
  if (eligible.length === 0) throw assetNotFound(depositArgs.mint);
301
- const acceptingDeposits = eligible.filter(
305
+ const unpaused = eligible.filter(
306
+ (market) => !(market.statusFlags & CLOB_STATUS_FLAG_PAUSED)
307
+ );
308
+ if (unpaused.length === 0) {
309
+ throw new ClobExchangeClientError(
310
+ 'market_paused',
311
+ 'no active CLOB market accepts deposits for this asset',
312
+ { mint: depositArgs.mint }
313
+ );
314
+ }
315
+ const acceptingDeposits = unpaused.filter(
302
316
  (market) => !(market.statusFlags & CLOB_STATUS_FLAG_DEPOSITS_FROZEN)
303
317
  );
304
318
  /* Preserve the builder's deposits_frozen error when every compatible
305
319
  market is frozen, but never prefer a frozen existing allocation over
306
320
  another market that can actually accept the deposit. */
307
321
  const market = chooseDepositMarket(
308
- acceptingDeposits.length > 0 ? acceptingDeposits : eligible,
322
+ acceptingDeposits.length > 0 ? acceptingDeposits : unpaused,
309
323
  allocations,
310
324
  depositArgs.authority,
311
325
  depositArgs.mint
312
326
  );
313
327
  const tokenSide = tokenSideForMint(market, depositArgs.mint);
314
- const seats = await readMarketSeats(market);
328
+ const [seats, wallet] = await Promise.all([
329
+ readMarketSeats(market),
330
+ readCanonicalWalletAccount(
331
+ depositArgs.authority,
332
+ depositArgs.mint,
333
+ args.tokenProgramAddress
334
+ ),
335
+ validateMarketVault(market, tokenSide, depositArgs.mint),
336
+ ]);
315
337
  const existingSeat = seats
316
338
  .filter((seat) => seat.seatAuthority === depositArgs.authority)
317
339
  .sort((a, b) => a.seatIndex - b.seatIndex)[0] ?? null;
318
- const wallet = await readCanonicalWalletAccount(
319
- depositArgs.authority,
320
- depositArgs.mint,
321
- args.tokenProgramAddress
322
- );
323
340
  if (wallet.amount < depositArgs.amount) {
324
341
  throw new ClobExchangeClientError(
325
342
  'insufficient_wallet_balance',
@@ -566,9 +583,15 @@ export function createClobExchangeClient(
566
583
  }
567
584
  }
568
585
 
569
- async function readMintSymbol(mint: string): Promise<string | null> {
586
+ async function readMintMetadata(
587
+ mint: string
588
+ ): Promise<{ symbol: string | null; decimals: number } | null> {
570
589
  try {
571
- return parseMintAccountData(await args.thruClient.accounts.get(mint)).ticker || null;
590
+ const parsed = parseMintAccountData(await args.thruClient.accounts.get(mint));
591
+ return {
592
+ symbol: parsed.ticker || null,
593
+ decimals: parsed.decimals,
594
+ };
572
595
  } catch (error) {
573
596
  if (isAccountNotFoundError(error)) return null;
574
597
  return null;
@@ -579,6 +602,22 @@ export function createClobExchangeClient(
579
602
  return parseSeatArenaAccount(await args.thruClient.accounts.get(market.address)).seats;
580
603
  }
581
604
 
605
+ async function validateMarketVault(
606
+ market: ClobTradingMarket,
607
+ tokenSide: ClobTokenSide,
608
+ mint: string
609
+ ): Promise<void> {
610
+ const vault = tokenSide === 'base' ? market.baseVault : market.quoteVault;
611
+ const parsed = parseTokenAccountData(await args.thruClient.accounts.get(vault));
612
+ if (parsed.mint !== mint || parsed.owner !== clobProgramAddress) {
613
+ throw new ClobExchangeClientError(
614
+ 'invalid_token_account',
615
+ 'selected market vault does not match the requested mint and CLOB program',
616
+ { market: market.address, vault, expectedMint: mint, actualMint: parsed.mint }
617
+ );
618
+ }
619
+ }
620
+
582
621
  async function wrapWithWalletTokenAccountInitialization(initArgs: {
583
622
  authority: string;
584
623
  mint: string;
@@ -30,6 +30,7 @@ const TOKEN_PROGRAM = address(2);
30
30
  const BASE_MINT = address(3);
31
31
  const QUOTE_MINT = address(4);
32
32
  const WALLET_QUOTE = address(5);
33
+ const EXCHANGE_META = address(250);
33
34
 
34
35
  describe('CLOB exchange balance SDK', () => {
35
36
  it('aggregates compatible physical allocations without losing transferability', () => {
@@ -569,10 +570,10 @@ describe('CLOB exchange balance SDK', () => {
569
570
 
570
571
  expect([
571
572
  bytes[0],
572
- bytes[24],
573
- bytes[48],
574
- bytes[72],
575
- bytes[96],
573
+ bytes[32],
574
+ bytes[56],
575
+ bytes[88],
576
+ bytes[112],
576
577
  ]).toEqual([
577
578
  CLOB_INSTRUCTION_MARKET_RECORD,
578
579
  CLOB_INSTRUCTION_TOKEN_WITHDRAW,
@@ -581,12 +582,12 @@ describe('CLOB exchange balance SDK', () => {
581
582
  CLOB_INSTRUCTION_CREATE_ORDER_ENTRY,
582
583
  ]);
583
584
  expect(bytes[1]).toBe(1);
584
- expect(bytes[25]).toBe(1);
585
- expect(bytes[49]).toBe(2);
586
- expect(bytes[73]).toBe(2);
587
- expect(bytes[98]).toBe(2);
588
- expect(readU16(bytes, 22)).toBe(0xffff);
589
- expect(readU16(bytes, 70)).toBe(0xffff);
585
+ expect(bytes[33]).toBe(1);
586
+ expect(bytes[57]).toBe(2);
587
+ expect(bytes[89]).toBe(2);
588
+ expect(bytes[114]).toBe(2);
589
+ expect(readU16(bytes, 24)).toBe(0xffff);
590
+ expect(readU16(bytes, 80)).toBe(0xffff);
590
591
  expect(instructionPlan.readWriteAccounts).toContain(source.address);
591
592
  expect(instructionPlan.readWriteAccounts).toContain(source.orderArena);
592
593
  expect(instructionPlan.readWriteAccounts).toContain(source.bidsCbook);
@@ -638,7 +639,7 @@ describe('CLOB exchange balance SDK', () => {
638
639
  });
639
640
  const bytes = await instructionPlan.instructionData(contextForPlan(instructionPlan));
640
641
 
641
- expect([bytes[0], bytes[24], bytes[48], bytes[72], bytes[96]]).toEqual([
642
+ expect([bytes[0], bytes[32], bytes[56], bytes[88], bytes[112]]).toEqual([
642
643
  CLOB_INSTRUCTION_MARKET_RECORD,
643
644
  CLOB_INSTRUCTION_TOKEN_WITHDRAW,
644
645
  CLOB_INSTRUCTION_MARKET_RECORD,
@@ -646,7 +647,7 @@ describe('CLOB exchange balance SDK', () => {
646
647
  CLOB_INSTRUCTION_CREATE_ORDER_ENTRY,
647
648
  ]);
648
649
  expect(readU32(bytes, 12)).toBe(3);
649
- expect(readU32(bytes, 60)).toBe(2);
650
+ expect(readU32(bytes, 68)).toBe(2);
650
651
  expect(instructionPlan.readWriteAccounts.filter((account) => account === target.address))
651
652
  .toHaveLength(1);
652
653
  });
@@ -691,7 +692,7 @@ describe('CLOB exchange balance SDK', () => {
691
692
  });
692
693
  const bytes = await instructionPlan.instructionData(contextForPlan(instructionPlan));
693
694
 
694
- expect([bytes[0], bytes[24], bytes[48], bytes[72], bytes[96], bytes[120], bytes[128], bytes[152]]).toEqual([
695
+ expect([bytes[0], bytes[32], bytes[56], bytes[88], bytes[112], bytes[144], bytes[152], bytes[176]]).toEqual([
695
696
  CLOB_INSTRUCTION_MARKET_RECORD,
696
697
  CLOB_INSTRUCTION_TOKEN_WITHDRAW,
697
698
  CLOB_INSTRUCTION_MARKET_RECORD,
@@ -701,7 +702,7 @@ describe('CLOB exchange balance SDK', () => {
701
702
  CLOB_INSTRUCTION_TOKEN_DEPOSIT,
702
703
  CLOB_INSTRUCTION_CREATE_ORDER_ENTRY,
703
704
  ]);
704
- expect([bytes[1], bytes[25], bytes[49], bytes[73], bytes[97], bytes[129], bytes[154]])
705
+ expect([bytes[1], bytes[33], bytes[57], bytes[89], bytes[113], bytes[153], bytes[178]])
705
706
  .toEqual([1, 1, 2, 2, 3, 3, 3]);
706
707
  expect(instructionPlan.review.value.sourceMarketCount).toBe('2');
707
708
  expect(instructionPlan.review.value.exchangeAmount).toBe('300');
@@ -744,7 +745,7 @@ describe('CLOB exchange balance SDK', () => {
744
745
  seatIndex: null,
745
746
  });
746
747
  const depositBytes = await deposit.instructionData(contextForPlan(deposit));
747
- expect([depositBytes[0], depositBytes[24], depositBytes[32]]).toEqual([
748
+ expect([depositBytes[0], depositBytes[32], depositBytes[40]]).toEqual([
748
749
  CLOB_INSTRUCTION_MARKET_RECORD,
749
750
  CLOB_INSTRUCTION_SEAT_CREATE,
750
751
  CLOB_INSTRUCTION_TOKEN_DEPOSIT,
@@ -760,7 +761,7 @@ describe('CLOB exchange balance SDK', () => {
760
761
  seatIndex: 2,
761
762
  });
762
763
  const withdrawalBytes = await withdrawal.instructionData(contextForPlan(withdrawal));
763
- expect([withdrawalBytes[0], withdrawalBytes[24]]).toEqual([
764
+ expect([withdrawalBytes[0], withdrawalBytes[32]]).toEqual([
764
765
  CLOB_INSTRUCTION_MARKET_RECORD,
765
766
  CLOB_INSTRUCTION_TOKEN_WITHDRAW,
766
767
  ]);
@@ -825,6 +826,7 @@ function market(
825
826
  ): ClobTradingMarket {
826
827
  return {
827
828
  address: address(id),
829
+ exchangeMeta: EXCHANGE_META,
828
830
  orderArena: address(id + 1),
829
831
  bidsCbook: address(id + 2),
830
832
  asksCbook: address(id + 3),
@@ -48,6 +48,7 @@ export interface ClobExchangeAssetBalance {
48
48
 
49
49
  export interface ClobTradingMarket {
50
50
  address: string;
51
+ exchangeMeta: string;
51
52
  orderArena: string;
52
53
  bidsCbook: string;
53
54
  asksCbook: string;
@@ -775,6 +776,7 @@ function marketRecordInstruction(
775
776
  asksCbookAccountBytes: addressBytes(market.asksCbook),
776
777
  seatAuthorityAccountBytes: authority ? addressBytes(authority) : undefined,
777
778
  seatIndex: seatIndex ?? undefined,
779
+ exchangeMetaAccountBytes: addressBytes(market.exchangeMeta),
778
780
  tokenProgramAccountBytes: addressBytes(market.tokenProgram),
779
781
  baseVaultAccountBytes: addressBytes(market.baseVault),
780
782
  quoteVaultAccountBytes: addressBytes(market.quoteVault),
@@ -788,6 +790,7 @@ function addTargetMarketAccounts(accounts: AccountPlan, market: ClobTradingMarke
788
790
  accounts.addWrite(market.asksCbook);
789
791
  accounts.addRead(market.baseVault);
790
792
  accounts.addRead(market.quoteVault);
793
+ accounts.addRead(market.exchangeMeta);
791
794
  }
792
795
 
793
796
  function addSourceMarketAccounts(
@@ -806,6 +809,7 @@ function addSourceMarketAccounts(
806
809
  accounts.addWrite(market.asksCbook);
807
810
  accounts.addRead(market.baseVault);
808
811
  accounts.addRead(market.quoteVault);
812
+ accounts.addRead(market.exchangeMeta);
809
813
  }
810
814
 
811
815
  class AccountPlan {
@@ -1,10 +1,19 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
  import { encodeAddress } from '@thru/sdk/helpers';
3
+ import { BOOTSTRAP_PROGRAM_ADDRESSES } from '../bootstrap-addresses';
3
4
  import {
5
+ CLOB_PROGRAM_ADDRESS,
4
6
  CLOB_INSTRUCTION_MARKET_RECORD,
5
7
  CLOB_NULL_INDEX,
6
8
  CLOB_INSTRUCTION_CREATE_ORDER_ENTRY,
7
9
  CLOB_INSTRUCTION_CREATE_SEATLESS_ORDER_ENTRY,
10
+ CLOB_INSTRUCTION_EXCHANGE_INITIALIZE,
11
+ CLOB_INSTRUCTION_EXCHANGE_SET_STATUS,
12
+ CLOB_INSTRUCTION_EXCHANGE_SET_ADMIN,
13
+ CLOB_INSTRUCTION_EXCHANGE_RECOVER_ADMIN,
14
+ CLOB_INSTRUCTION_MARKET_SET_EXCHANGE_STATUS,
15
+ CLOB_EXCHANGE_META_MAGIC,
16
+ CLOB_EXCHANGE_META_VERSION,
8
17
  CLOB_CBOOK_MAX_PRICE_IN_TICKS,
9
18
  CLOB_EVENT_SIDE_BUY,
10
19
  CLOB_ORDER_FLAG_BUY,
@@ -13,18 +22,30 @@ import {
13
22
  CLOB_ORDER_TYPE_GTC,
14
23
  CLOB_ORDER_TYPE_IOC,
15
24
  CLOB_ORDER_TYPE_MTL,
25
+ CLOB_STATUS_FLAG_DEPOSITS_FROZEN,
26
+ CLOB_STATUS_FLAG_PAUSED,
27
+ CLOB_STATUS_FLAG_POST_ONLY,
28
+ CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN,
16
29
  ClobEventBuilder,
30
+ ExchangeMetaAccountBuilder,
17
31
  MarketAccountBuilder,
18
32
  MarketCreatedEventBuilder,
19
33
  OrderEntryBuilder,
20
34
  OrderFilledEventBuilder,
21
35
  SeatEntryBuilder,
22
36
  buildOrderBookSnapshot,
37
+ createExchangeInitializeInstruction,
38
+ createExchangeSetStatusInstruction,
39
+ createExchangeSetAdminInstruction,
40
+ createExchangeRecoverAdminInstruction,
41
+ createMarketSetExchangeStatusInstruction,
23
42
  createMarketRecordInstruction,
24
43
  createOrderEntryInstruction,
25
44
  createSeatlessOrderEntryInstruction,
45
+ effectiveClobStatusFlags,
26
46
  encodeOrderFlags,
27
47
  parseClobEvent,
48
+ parseExchangeMetaAccount,
28
49
  parseMarketAccount,
29
50
  parseOrderArenaAccount,
30
51
  parseSeatArenaAccount,
@@ -47,17 +68,22 @@ function context(indexes: Record<string, number>) {
47
68
  }
48
69
 
49
70
  describe('clob helpers', () => {
71
+ it('uses the bootstrap-managed CLOB program address', () => {
72
+ expect(CLOB_PROGRAM_ADDRESS).toBe(BOOTSTRAP_PROGRAM_ADDRESSES.clob);
73
+ });
74
+
50
75
  it('validates market-record seat indices before ABI serialization', async () => {
51
- const accounts = Array.from({ length: 7 }, (_, index) => key(index + 1));
76
+ const accounts = Array.from({ length: 8 }, (_, index) => key(index + 1));
52
77
  const args = {
53
78
  marketRecordIndex: 1,
54
79
  seatArenaAccountBytes: accounts[0],
55
80
  orderArenaAccountBytes: accounts[1],
56
81
  bidsCbookAccountBytes: accounts[2],
57
82
  asksCbookAccountBytes: accounts[3],
58
- tokenProgramAccountBytes: accounts[4],
59
- baseVaultAccountBytes: accounts[5],
60
- quoteVaultAccountBytes: accounts[6],
83
+ exchangeMetaAccountBytes: accounts[4],
84
+ tokenProgramAccountBytes: accounts[5],
85
+ baseVaultAccountBytes: accounts[6],
86
+ quoteVaultAccountBytes: accounts[7],
61
87
  };
62
88
  const lookup = context(Object.fromEntries(
63
89
  accounts.map((account, index) => [bytesToHex(account), index + 2])
@@ -76,6 +102,113 @@ describe('clob helpers', () => {
76
102
  }
77
103
  });
78
104
 
105
+ it('builds and parses exchange metadata instructions and accounts', async () => {
106
+ const exchangeMeta = key(1);
107
+ const programMeta = key(2);
108
+ const authority = key(3);
109
+ const tokenProgram = key(4);
110
+ const exchangeAdmin = key(5);
111
+ const proof = new Uint8Array([6, 7, 8]);
112
+ const instruction = await createExchangeInitializeInstruction({
113
+ exchangeMetaAccountBytes: exchangeMeta,
114
+ programMetaAccountBytes: programMeta,
115
+ authorityAccountBytes: authority,
116
+ tokenProgramAccountBytes: tokenProgram,
117
+ exchangeAdminAccountBytes: exchangeAdmin,
118
+ stateProof: proof,
119
+ })(context({
120
+ [bytesToHex(exchangeMeta)]: 10,
121
+ [bytesToHex(programMeta)]: 11,
122
+ [bytesToHex(authority)]: 12,
123
+ [bytesToHex(tokenProgram)]: 13,
124
+ [bytesToHex(exchangeAdmin)]: 14,
125
+ }));
126
+
127
+ expect(instruction[0]).toBe(CLOB_INSTRUCTION_EXCHANGE_INITIALIZE);
128
+ const view = new DataView(instruction.buffer, instruction.byteOffset, instruction.byteLength);
129
+ expect(view.getUint16(2, true)).toBe(10);
130
+ expect(view.getUint16(4, true)).toBe(11);
131
+ expect(view.getUint16(6, true)).toBe(12);
132
+ expect(view.getUint16(8, true)).toBe(13);
133
+ expect(view.getUint16(10, true)).toBe(14);
134
+ expect(view.getUint32(12, true)).toBe(proof.length);
135
+ expect(instruction.slice(16)).toEqual(proof);
136
+
137
+ const data = new ExchangeMetaAccountBuilder()
138
+ .set_magic(CLOB_EXCHANGE_META_MAGIC)
139
+ .set_version(CLOB_EXCHANGE_META_VERSION)
140
+ .set_status_flags(3)
141
+ .set_reserved0([0, 0, 0, 0, 0, 0])
142
+ .set_token_program_pubkey(tokenProgram)
143
+ .set_exchange_admin_pubkey(exchangeAdmin)
144
+ .set_reserved1(new Uint8Array(16))
145
+ .build();
146
+ expect(parseExchangeMetaAccount(data)).toEqual({
147
+ magic: CLOB_EXCHANGE_META_MAGIC,
148
+ version: CLOB_EXCHANGE_META_VERSION,
149
+ statusFlags: 3,
150
+ tokenProgram: bytesToAddress(tokenProgram),
151
+ exchangeAdmin: bytesToAddress(exchangeAdmin),
152
+ });
153
+ });
154
+
155
+ it('builds exchange administration instructions', async () => {
156
+ const exchangeMeta = key(1);
157
+ const admin = key(2);
158
+ const nextAdmin = key(3);
159
+ const programMeta = key(4);
160
+ const lookup = context({
161
+ [bytesToHex(exchangeMeta)]: 10,
162
+ [bytesToHex(admin)]: 11,
163
+ [bytesToHex(nextAdmin)]: 12,
164
+ [bytesToHex(programMeta)]: 13,
165
+ });
166
+
167
+ const setStatus = await createExchangeSetStatusInstruction({
168
+ exchangeMetaAccountBytes: exchangeMeta,
169
+ exchangeAdminAccountBytes: admin,
170
+ statusFlags: 5,
171
+ })(lookup);
172
+ const setAdmin = await createExchangeSetAdminInstruction({
173
+ exchangeMetaAccountBytes: exchangeMeta,
174
+ authorityAccountBytes: admin,
175
+ newAdminAccountBytes: nextAdmin,
176
+ })(lookup);
177
+ const recoverAdmin = await createExchangeRecoverAdminInstruction({
178
+ exchangeMetaAccountBytes: exchangeMeta,
179
+ programMetaAccountBytes: programMeta,
180
+ authorityAccountBytes: admin,
181
+ newAdminAccountBytes: nextAdmin,
182
+ })(lookup);
183
+ const marketOverride = await createMarketSetExchangeStatusInstruction({
184
+ marketRecordIndex: 7,
185
+ exchangeAdminAccountBytes: admin,
186
+ statusFlags: 2,
187
+ })(lookup);
188
+
189
+ expect(setStatus[0]).toBe(CLOB_INSTRUCTION_EXCHANGE_SET_STATUS);
190
+ expect(setAdmin[0]).toBe(CLOB_INSTRUCTION_EXCHANGE_SET_ADMIN);
191
+ expect(recoverAdmin[0]).toBe(CLOB_INSTRUCTION_EXCHANGE_RECOVER_ADMIN);
192
+ expect(marketOverride[0]).toBe(CLOB_INSTRUCTION_MARKET_SET_EXCHANGE_STATUS);
193
+ await expect(createExchangeSetStatusInstruction({
194
+ exchangeMetaAccountBytes: exchangeMeta,
195
+ exchangeAdminAccountBytes: admin,
196
+ statusFlags: 16,
197
+ })(lookup)).rejects.toThrow(/statusFlags/);
198
+ });
199
+
200
+ it('combines global, exchange-admin, and market-authority status flags', () => {
201
+ expect(effectiveClobStatusFlags(
202
+ CLOB_STATUS_FLAG_PAUSED,
203
+ {
204
+ statusFlags: CLOB_STATUS_FLAG_POST_ONLY,
205
+ exchangeStatusFlags: CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN | CLOB_STATUS_FLAG_DEPOSITS_FROZEN,
206
+ },
207
+ )).toBe(15);
208
+ expect(() => effectiveClobStatusFlags(16, { statusFlags: 0, exchangeStatusFlags: 0 }))
209
+ .toThrow(/statusFlags/);
210
+ });
211
+
79
212
  it('encodes order flags with C program bit semantics', () => {
80
213
  expect(encodeOrderFlags({ side: 'buy', orderType: 'gtc' })).toBe(
81
214
  CLOB_ORDER_FLAG_BUY | (CLOB_ORDER_TYPE_GTC << 1)
@@ -134,14 +267,14 @@ describe('clob helpers', () => {
134
267
  const data = new MarketAccountBuilder()
135
268
  .set_magic(0xc1)
136
269
  .set_status_flags(3)
137
- .set_reserved0([0, 0, 0, 0, 0, 0])
270
+ .set_exchange_status_flags(4)
271
+ .set_reserved0([0, 0, 0, 0, 0])
138
272
  .set_lot_size(100n)
139
273
  .set_tick_size(5n)
140
274
  .set_next_order_id(42n)
141
275
  .set_order_entry_pubkey(key(10))
142
276
  .set_bids_cbook_pubkey(key(11))
143
277
  .set_asks_cbook_pubkey(key(12))
144
- .set_token_program_pubkey(key(16))
145
278
  .set_base_vault_pubkey(key(13))
146
279
  .set_quote_vault_pubkey(key(14))
147
280
  .set_market_authority_pubkey(key(15))
@@ -150,11 +283,11 @@ describe('clob helpers', () => {
150
283
  const market = parseMarketAccount(data);
151
284
  expect(market.magic).toBe(0xc1);
152
285
  expect(market.statusFlags).toBe(3);
286
+ expect(market.exchangeStatusFlags).toBe(4);
153
287
  expect(market.lotSize).toBe(100n);
154
288
  expect(market.tickSize).toBe(5n);
155
289
  expect(market.nextOrderId).toBe(42n);
156
290
  expect(market.bidsCbook).not.toBe(market.asksCbook);
157
- expect(market.tokenProgram).toBe(bytesToAddress(key(16)));
158
291
  });
159
292
 
160
293
  it('parses order arenas and groups active orderbook depth', () => {