@thru/programs 0.3.2 → 0.3.4

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,914 @@
1
+ import { Pubkey } from '@thru/sdk';
2
+ import type { Thru } from '@thru/sdk/client';
3
+ import {
4
+ createInitializeAccountInstruction,
5
+ deriveTokenAccountAddress,
6
+ isAccountNotFoundError,
7
+ parseMintAccountData,
8
+ parseTokenAccountData,
9
+ } from '../token';
10
+ import {
11
+ aggregateClobExchangeBalances,
12
+ buildClobExchangeDepositInstructionPlan,
13
+ buildClobExchangeWithdrawalInstructionPlan,
14
+ buildClobFundedOrderInstructionPlan,
15
+ planClobOrderFunding,
16
+ validateClobOrderFundingPlanSeats,
17
+ wrapClobPlanWithTokenAccountInitialization,
18
+ type ClobAssetBalanceAllocation,
19
+ type ClobInstructionPlan,
20
+ type ClobOrderFundingPlan,
21
+ type ClobTradingMarket,
22
+ type ClobTransactionPlan,
23
+ } from './exchange';
24
+ import {
25
+ CLOB_PROGRAM_ADDRESS,
26
+ CLOB_STATUS_FLAG_DEPOSITS_FROZEN,
27
+ CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN,
28
+ parseSeatArenaAccount,
29
+ type ClobOrderSide,
30
+ type ClobOrderType,
31
+ type ClobSeatEntry,
32
+ type ClobTokenSide,
33
+ } from './index';
34
+
35
+ const TOKEN_ACCOUNT_DEFAULT_SEED = new Uint8Array(32);
36
+ const STATE_PROOF_TYPE_CREATING = 1;
37
+ const DEFAULT_ORDER_EXPIRATION_TIME = 9_223_372_036_854_775_807n;
38
+
39
+ export interface ClobExchangeDataSource {
40
+ getMarkets(): Promise<ClobMarketDiscovery>;
41
+ getAssetAllocations(authority: string): Promise<ClobAssetBalanceAllocation[]>;
42
+ }
43
+
44
+ export interface ClobUnavailableMarket {
45
+ market: string;
46
+ baseMint: string | null;
47
+ quoteMint: string | null;
48
+ reason: string;
49
+ }
50
+
51
+ export interface ClobMarketDiscovery {
52
+ markets: ClobTradingMarket[];
53
+ unavailableMarkets: ClobUnavailableMarket[];
54
+ }
55
+
56
+ export interface ClobWalletTokenAccountSnapshot {
57
+ tokenAccount: string;
58
+ amount: bigint;
59
+ exists: boolean;
60
+ }
61
+
62
+ export interface ClobExchangeAssetSnapshot {
63
+ mint: string;
64
+ tokenProgram: string;
65
+ symbol: string | null;
66
+ discoveryComplete: boolean;
67
+ exchange: {
68
+ freeAmount: bigint;
69
+ transferableAmount: bigint;
70
+ allocations: ClobAssetBalanceAllocation[];
71
+ };
72
+ wallet: ClobWalletTokenAccountSnapshot;
73
+ }
74
+
75
+ export interface ClobExchangeAccountSnapshot {
76
+ authority: string;
77
+ assets: ClobExchangeAssetSnapshot[];
78
+ unavailableMarkets: ClobUnavailableMarket[];
79
+ }
80
+
81
+ export interface ClobBalanceEffect {
82
+ location: 'wallet' | 'exchange';
83
+ mint: string;
84
+ tokenProgram: string;
85
+ delta: bigint;
86
+ market?: string;
87
+ }
88
+
89
+ export interface ClobPreparedOperation {
90
+ plan: ClobTransactionPlan;
91
+ effects: ClobBalanceEffect[];
92
+ }
93
+
94
+ export interface ClobPreparedDeposit extends ClobPreparedOperation {
95
+ market: ClobTradingMarket;
96
+ tokenSide: ClobTokenSide;
97
+ seatIndex: number | null;
98
+ walletTokenAccount: ClobWalletTokenAccountSnapshot;
99
+ }
100
+
101
+ export interface ClobPreparedWithdrawal extends ClobPreparedOperation {
102
+ market: ClobTradingMarket;
103
+ tokenSide: ClobTokenSide;
104
+ seatIndex: number;
105
+ walletTokenAccount: ClobWalletTokenAccountSnapshot;
106
+ }
107
+
108
+ export interface ClobPreparedOrder extends ClobPreparedOperation {
109
+ market: ClobTradingMarket;
110
+ funding: ClobOrderFundingPlan;
111
+ sourceMarkets: ClobTradingMarket[];
112
+ walletTokenAccount: ClobWalletTokenAccountSnapshot;
113
+ }
114
+
115
+ export type ClobExchangeClientErrorCode =
116
+ | 'data_source_unavailable'
117
+ | 'incomplete_market_metadata'
118
+ | 'asset_not_found'
119
+ | 'ambiguous_asset'
120
+ | 'invalid_amount'
121
+ | 'insufficient_wallet_balance'
122
+ | 'insufficient_exchange_balance'
123
+ | 'fragmented_balance'
124
+ | 'invalid_token_account';
125
+
126
+ export class ClobExchangeClientError extends Error {
127
+ readonly code: ClobExchangeClientErrorCode;
128
+ readonly details?: Readonly<Record<string, string>>;
129
+
130
+ constructor(
131
+ code: ClobExchangeClientErrorCode,
132
+ message: string,
133
+ details?: Readonly<Record<string, string>>
134
+ ) {
135
+ super(message);
136
+ this.name = 'ClobExchangeClientError';
137
+ this.code = code;
138
+ this.details = details;
139
+ }
140
+ }
141
+
142
+ export interface CreateClobExchangeClientArgs {
143
+ thruClient: Thru;
144
+ dataSource: ClobExchangeDataSource;
145
+ tokenProgramAddress: string;
146
+ clobProgramAddress?: string;
147
+ }
148
+
149
+ export interface PrepareClobDepositArgs {
150
+ authority: string;
151
+ mint: string;
152
+ amount: bigint;
153
+ }
154
+
155
+ export interface PrepareClobWithdrawalArgs extends PrepareClobDepositArgs {}
156
+
157
+ export interface PrepareClobOrderArgs {
158
+ authority: string;
159
+ market: string | ClobTradingMarket;
160
+ side: ClobOrderSide;
161
+ orderType?: ClobOrderType;
162
+ price: bigint;
163
+ quantity: bigint;
164
+ expirationTime?: bigint;
165
+ clientId?: Uint8Array;
166
+ discardAfterMatch?: boolean;
167
+ failIfOutsideBook?: boolean;
168
+ targetSeatIndex?: number;
169
+ }
170
+
171
+ export interface ClobWithdrawalCapacity {
172
+ mint: string;
173
+ tokenProgram: string;
174
+ total: bigint;
175
+ maximumSingleAllocation: bigint;
176
+ }
177
+
178
+ export interface ClobExchangeClient {
179
+ getAccountSnapshot(args: { authority: string }): Promise<ClobExchangeAccountSnapshot>;
180
+ getWithdrawalCapacity(args: { authority: string; mint: string }): Promise<ClobWithdrawalCapacity>;
181
+ prepareDeposit(args: PrepareClobDepositArgs): Promise<ClobPreparedDeposit>;
182
+ prepareWithdrawal(args: PrepareClobWithdrawalArgs): Promise<ClobPreparedWithdrawal>;
183
+ prepareOrder(args: PrepareClobOrderArgs): Promise<ClobPreparedOrder>;
184
+ }
185
+
186
+ export function createClobExchangeClient(
187
+ args: CreateClobExchangeClientArgs
188
+ ): ClobExchangeClient {
189
+ const clobProgramAddress = args.clobProgramAddress ?? CLOB_PROGRAM_ADDRESS;
190
+
191
+ async function loadState(authority: string): Promise<{
192
+ markets: ClobTradingMarket[];
193
+ allocations: ClobAssetBalanceAllocation[];
194
+ unavailableMarkets: ClobUnavailableMarket[];
195
+ }> {
196
+ try {
197
+ const [discovery, allocations] = await Promise.all([
198
+ args.dataSource.getMarkets(),
199
+ args.dataSource.getAssetAllocations(authority),
200
+ ]);
201
+ for (const market of discovery.markets) validateMarketMetadata(market);
202
+ return {
203
+ markets: sortMarkets(discovery.markets),
204
+ allocations,
205
+ unavailableMarkets: discovery.unavailableMarkets,
206
+ };
207
+ } catch (error) {
208
+ if (error instanceof ClobExchangeClientError) throw error;
209
+ throw new ClobExchangeClientError(
210
+ 'data_source_unavailable',
211
+ 'CLOB exchange data source is unavailable',
212
+ { cause: errorMessage(error) }
213
+ );
214
+ }
215
+ }
216
+
217
+ async function getAccountSnapshot(
218
+ snapshotArgs: { authority: string }
219
+ ): Promise<ClobExchangeAccountSnapshot> {
220
+ const { authority } = snapshotArgs;
221
+ const { markets, allocations, unavailableMarkets } = await loadState(authority);
222
+ const balances = new Map(
223
+ aggregateClobExchangeBalances(allocations)
224
+ .filter((balance) => balance.authority === authority)
225
+ .map((balance) => [assetKey(balance.mint, balance.tokenProgram), balance])
226
+ );
227
+ const assets = uniqueSnapshotAssets(markets, allocations, authority);
228
+ const snapshots = await Promise.all(assets.map(async ({ mint, tokenProgram }) => {
229
+ const balance = balances.get(assetKey(mint, tokenProgram));
230
+ const [wallet, symbol] = await Promise.all([
231
+ readCanonicalWalletAccount(authority, mint, tokenProgram),
232
+ readMintSymbol(mint),
233
+ ]);
234
+ return {
235
+ mint,
236
+ tokenProgram,
237
+ symbol,
238
+ discoveryComplete: isAssetDiscoveryComplete(
239
+ unavailableMarkets,
240
+ balance?.allocations ?? [],
241
+ mint
242
+ ),
243
+ exchange: {
244
+ freeAmount: balance?.freeAmount ?? 0n,
245
+ transferableAmount: balance?.transferableAmount ?? 0n,
246
+ allocations: balance?.allocations ?? [],
247
+ },
248
+ wallet,
249
+ } satisfies ClobExchangeAssetSnapshot;
250
+ }));
251
+ return { authority, assets: snapshots, unavailableMarkets };
252
+ }
253
+
254
+ async function getWithdrawalCapacity(
255
+ capacityArgs: { authority: string; mint: string }
256
+ ): Promise<ClobWithdrawalCapacity> {
257
+ const { markets, allocations, unavailableMarkets } = await loadState(capacityArgs.authority);
258
+ assertAssetDiscoveryComplete(
259
+ unavailableMarkets,
260
+ allocations,
261
+ capacityArgs.authority,
262
+ capacityArgs.mint
263
+ );
264
+ const candidates = withdrawalAllocations(
265
+ allocations,
266
+ markets,
267
+ capacityArgs.authority,
268
+ capacityArgs.mint,
269
+ args.tokenProgramAddress
270
+ );
271
+ const fresh = await freshWithdrawalAllocations(
272
+ candidates,
273
+ markets,
274
+ capacityArgs.authority,
275
+ readMarketSeats
276
+ );
277
+ return {
278
+ mint: capacityArgs.mint,
279
+ tokenProgram: args.tokenProgramAddress,
280
+ total: fresh.reduce((sum, entry) => sum + entry.amount, 0n),
281
+ maximumSingleAllocation: fresh.reduce(
282
+ (maximum, entry) => entry.amount > maximum ? entry.amount : maximum,
283
+ 0n
284
+ ),
285
+ };
286
+ }
287
+
288
+ async function prepareDeposit(
289
+ depositArgs: PrepareClobDepositArgs
290
+ ): Promise<ClobPreparedDeposit> {
291
+ assertPositiveAmount(depositArgs.amount);
292
+ const { markets, allocations, unavailableMarkets } = await loadState(depositArgs.authority);
293
+ assertAssetDiscoveryComplete(
294
+ unavailableMarkets,
295
+ allocations,
296
+ depositArgs.authority,
297
+ depositArgs.mint
298
+ );
299
+ const eligible = marketsForAsset(markets, depositArgs.mint, args.tokenProgramAddress);
300
+ if (eligible.length === 0) throw assetNotFound(depositArgs.mint);
301
+ const acceptingDeposits = eligible.filter(
302
+ (market) => !(market.statusFlags & CLOB_STATUS_FLAG_DEPOSITS_FROZEN)
303
+ );
304
+ /* Preserve the builder's deposits_frozen error when every compatible
305
+ market is frozen, but never prefer a frozen existing allocation over
306
+ another market that can actually accept the deposit. */
307
+ const market = chooseDepositMarket(
308
+ acceptingDeposits.length > 0 ? acceptingDeposits : eligible,
309
+ allocations,
310
+ depositArgs.authority,
311
+ depositArgs.mint
312
+ );
313
+ const tokenSide = tokenSideForMint(market, depositArgs.mint);
314
+ const seats = await readMarketSeats(market);
315
+ const existingSeat = seats
316
+ .filter((seat) => seat.seatAuthority === depositArgs.authority)
317
+ .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
+ if (wallet.amount < depositArgs.amount) {
324
+ throw new ClobExchangeClientError(
325
+ 'insufficient_wallet_balance',
326
+ 'wallet balance is insufficient for this deposit',
327
+ { available: wallet.amount.toString(), required: depositArgs.amount.toString() }
328
+ );
329
+ }
330
+ const plan = withClobProgram(buildClobExchangeDepositInstructionPlan({
331
+ market,
332
+ authority: depositArgs.authority,
333
+ walletTokenAccount: wallet.tokenAccount,
334
+ tokenSide,
335
+ amount: depositArgs.amount,
336
+ seatIndex: existingSeat?.seatIndex ?? null,
337
+ }));
338
+ return {
339
+ plan,
340
+ effects: transferEffects(
341
+ depositArgs.mint,
342
+ args.tokenProgramAddress,
343
+ depositArgs.amount,
344
+ market.address,
345
+ 'wallet'
346
+ ),
347
+ market,
348
+ tokenSide,
349
+ seatIndex: existingSeat?.seatIndex ?? null,
350
+ walletTokenAccount: wallet,
351
+ };
352
+ }
353
+
354
+ async function prepareWithdrawal(
355
+ withdrawalArgs: PrepareClobWithdrawalArgs
356
+ ): Promise<ClobPreparedWithdrawal> {
357
+ assertPositiveAmount(withdrawalArgs.amount);
358
+ const { markets, allocations, unavailableMarkets } = await loadState(withdrawalArgs.authority);
359
+ assertAssetDiscoveryComplete(
360
+ unavailableMarkets,
361
+ allocations,
362
+ withdrawalArgs.authority,
363
+ withdrawalArgs.mint
364
+ );
365
+ const indexed = withdrawalAllocations(
366
+ allocations,
367
+ markets,
368
+ withdrawalArgs.authority,
369
+ withdrawalArgs.mint,
370
+ args.tokenProgramAddress
371
+ );
372
+ const fresh = await freshWithdrawalAllocations(
373
+ indexed,
374
+ markets,
375
+ withdrawalArgs.authority,
376
+ readMarketSeats
377
+ );
378
+ const selected = fresh
379
+ .filter((candidate) => candidate.amount >= withdrawalArgs.amount)
380
+ .sort((a, b) => compareBigInt(a.amount, b.amount)
381
+ || compareText(a.allocation.market, b.allocation.market)
382
+ || a.allocation.seatIndex - b.allocation.seatIndex)[0];
383
+ if (!selected) {
384
+ const total = fresh.reduce((sum, candidate) => sum + candidate.amount, 0n);
385
+ if (total >= withdrawalArgs.amount) {
386
+ throw new ClobExchangeClientError(
387
+ 'fragmented_balance',
388
+ 'withdrawal amount is split across multiple market seats',
389
+ { available: total.toString(), required: withdrawalArgs.amount.toString() }
390
+ );
391
+ }
392
+ throw new ClobExchangeClientError(
393
+ 'insufficient_exchange_balance',
394
+ 'exchange balance is insufficient for this withdrawal',
395
+ { available: total.toString(), required: withdrawalArgs.amount.toString() }
396
+ );
397
+ }
398
+ const market = marketByAddress(markets, selected.allocation.market);
399
+ const wallet = await readCanonicalWalletAccount(
400
+ withdrawalArgs.authority,
401
+ withdrawalArgs.mint,
402
+ args.tokenProgramAddress
403
+ );
404
+ let plan = withClobProgram(buildClobExchangeWithdrawalInstructionPlan({
405
+ market,
406
+ authority: withdrawalArgs.authority,
407
+ walletTokenAccount: wallet.tokenAccount,
408
+ tokenSide: selected.allocation.tokenSide,
409
+ amount: withdrawalArgs.amount,
410
+ seatIndex: selected.allocation.seatIndex,
411
+ }));
412
+ if (!wallet.exists) {
413
+ plan = await wrapWithWalletTokenAccountInitialization({
414
+ authority: withdrawalArgs.authority,
415
+ mint: withdrawalArgs.mint,
416
+ tokenProgram: args.tokenProgramAddress,
417
+ walletTokenAccount: wallet.tokenAccount,
418
+ plan,
419
+ });
420
+ }
421
+ return {
422
+ plan,
423
+ effects: transferEffects(
424
+ withdrawalArgs.mint,
425
+ args.tokenProgramAddress,
426
+ withdrawalArgs.amount,
427
+ market.address,
428
+ 'exchange'
429
+ ),
430
+ market,
431
+ tokenSide: selected.allocation.tokenSide,
432
+ seatIndex: selected.allocation.seatIndex,
433
+ walletTokenAccount: wallet,
434
+ };
435
+ }
436
+
437
+ async function prepareOrder(orderArgs: PrepareClobOrderArgs): Promise<ClobPreparedOrder> {
438
+ const { markets, allocations, unavailableMarkets } = await loadState(orderArgs.authority);
439
+ if (typeof orderArgs.market === 'string') {
440
+ assertTargetMarketAvailable(unavailableMarkets, orderArgs.market);
441
+ }
442
+ const market = typeof orderArgs.market === 'string'
443
+ ? marketByAddress(markets, orderArgs.market)
444
+ : orderArgs.market;
445
+ validateMarketMetadata(market);
446
+ const fundingMint = (orderArgs.side === 'buy' ? market.quoteMint : market.baseMint)!;
447
+ assertAssetDiscoveryComplete(
448
+ unavailableMarkets,
449
+ allocations,
450
+ orderArgs.authority,
451
+ fundingMint,
452
+ market.address
453
+ );
454
+ const funding = planClobOrderFunding({
455
+ authority: orderArgs.authority,
456
+ targetMarket: market,
457
+ side: orderArgs.side,
458
+ orderType: orderArgs.orderType,
459
+ price: orderArgs.price,
460
+ quantity: orderArgs.quantity,
461
+ allocations,
462
+ targetSeatIndex: orderArgs.targetSeatIndex,
463
+ });
464
+ if (funding.shortfall > 0n) {
465
+ throw new ClobExchangeClientError(
466
+ 'insufficient_exchange_balance',
467
+ 'exchange balance is insufficient for this order',
468
+ {
469
+ available: funding.exchangeAvailableAmount.toString(),
470
+ required: funding.requiredAmount.toString(),
471
+ shortfall: funding.shortfall.toString(),
472
+ }
473
+ );
474
+ }
475
+ const sourceMarkets = [...new Set(
476
+ funding.sources
477
+ .map((source) => source.allocation.market)
478
+ .filter((address) => address !== market.address)
479
+ )].map((address) => marketByAddress(markets, address));
480
+ const [targetSeats, sourceSeatEntries] = await Promise.all([
481
+ readMarketSeats(market),
482
+ Promise.all(sourceMarkets.map(async (source) => [
483
+ source.address,
484
+ await readMarketSeats(source),
485
+ ] as const)),
486
+ ]);
487
+ validateClobOrderFundingPlanSeats({
488
+ plan: funding,
489
+ targetSeats,
490
+ sourceSeatsByMarket: Object.fromEntries(sourceSeatEntries),
491
+ });
492
+ const wallet = await readCanonicalWalletAccount(
493
+ orderArgs.authority,
494
+ funding.mint,
495
+ funding.tokenProgram
496
+ );
497
+ let plan = withClobProgram(buildClobFundedOrderInstructionPlan({
498
+ plan: funding,
499
+ targetMarket: market,
500
+ sourceMarkets,
501
+ walletTokenAccount: wallet.tokenAccount,
502
+ price: orderArgs.price,
503
+ quantity: orderArgs.quantity,
504
+ orderType: orderArgs.orderType,
505
+ expirationTime: orderArgs.expirationTime ?? DEFAULT_ORDER_EXPIRATION_TIME,
506
+ clientId: orderArgs.clientId,
507
+ discardAfterMatch: orderArgs.discardAfterMatch,
508
+ failIfOutsideBook: orderArgs.failIfOutsideBook,
509
+ }));
510
+ if (funding.sources.length > 0 && !wallet.exists) {
511
+ plan = await wrapWithWalletTokenAccountInitialization({
512
+ authority: orderArgs.authority,
513
+ mint: funding.mint,
514
+ tokenProgram: funding.tokenProgram,
515
+ walletTokenAccount: wallet.tokenAccount,
516
+ plan,
517
+ });
518
+ }
519
+ return {
520
+ plan,
521
+ /* Internal source-seat withdrawals and target-seat deposits cancel
522
+ at the exchange-account level. Fill effects arrive from indexed
523
+ chain state, so preparation must not predict them. */
524
+ effects: [{
525
+ location: 'exchange',
526
+ mint: funding.mint,
527
+ tokenProgram: funding.tokenProgram,
528
+ delta: -funding.requiredAmount,
529
+ market: market.address,
530
+ }],
531
+ market,
532
+ funding,
533
+ sourceMarkets,
534
+ walletTokenAccount: wallet,
535
+ };
536
+ }
537
+
538
+ async function readCanonicalWalletAccount(
539
+ authority: string,
540
+ mint: string,
541
+ tokenProgram: string
542
+ ): Promise<ClobWalletTokenAccountSnapshot> {
543
+ const derived = deriveTokenAccountAddress(
544
+ args.thruClient,
545
+ authority,
546
+ mint,
547
+ tokenProgram,
548
+ TOKEN_ACCOUNT_DEFAULT_SEED
549
+ );
550
+ try {
551
+ const account = await args.thruClient.accounts.get(derived.address);
552
+ const parsed = parseTokenAccountData(account);
553
+ if (parsed.mint !== mint || parsed.owner !== authority) {
554
+ throw new ClobExchangeClientError(
555
+ 'invalid_token_account',
556
+ 'canonical token account does not match the requested owner and mint',
557
+ { tokenAccount: derived.address }
558
+ );
559
+ }
560
+ return { tokenAccount: derived.address, amount: parsed.amount, exists: true };
561
+ } catch (error) {
562
+ if (isAccountNotFoundError(error)) {
563
+ return { tokenAccount: derived.address, amount: 0n, exists: false };
564
+ }
565
+ throw error;
566
+ }
567
+ }
568
+
569
+ async function readMintSymbol(mint: string): Promise<string | null> {
570
+ try {
571
+ return parseMintAccountData(await args.thruClient.accounts.get(mint)).ticker || null;
572
+ } catch (error) {
573
+ if (isAccountNotFoundError(error)) return null;
574
+ return null;
575
+ }
576
+ }
577
+
578
+ async function readMarketSeats(market: ClobTradingMarket): Promise<ClobSeatEntry[]> {
579
+ return parseSeatArenaAccount(await args.thruClient.accounts.get(market.address)).seats;
580
+ }
581
+
582
+ async function wrapWithWalletTokenAccountInitialization(initArgs: {
583
+ authority: string;
584
+ mint: string;
585
+ tokenProgram: string;
586
+ walletTokenAccount: string;
587
+ plan: ClobInstructionPlan;
588
+ }): Promise<ClobTransactionPlan> {
589
+ const derived = deriveTokenAccountAddress(
590
+ args.thruClient,
591
+ initArgs.authority,
592
+ initArgs.mint,
593
+ initArgs.tokenProgram,
594
+ TOKEN_ACCOUNT_DEFAULT_SEED
595
+ );
596
+ if (derived.address !== initArgs.walletTokenAccount) {
597
+ throw new ClobExchangeClientError(
598
+ 'invalid_token_account',
599
+ 'wallet token account is not canonical'
600
+ );
601
+ }
602
+ const proof = await args.thruClient.proofs.generate({
603
+ address: derived.address,
604
+ proofType: STATE_PROOF_TYPE_CREATING,
605
+ });
606
+ if (!proof.proof?.length) {
607
+ throw new ClobExchangeClientError(
608
+ 'invalid_token_account',
609
+ 'state proof is required to initialize the wallet token account'
610
+ );
611
+ }
612
+ return wrapClobPlanWithTokenAccountInitialization({
613
+ plan: initArgs.plan,
614
+ clobProgram: clobProgramAddress,
615
+ initialization: {
616
+ instructionData: createInitializeAccountInstruction({
617
+ tokenAccountBytes: derived.bytes,
618
+ mintAccountBytes: Pubkey.from(initArgs.mint).toBytes(),
619
+ ownerAccountBytes: Pubkey.from(initArgs.authority).toBytes(),
620
+ seedBytes: TOKEN_ACCOUNT_DEFAULT_SEED,
621
+ stateProof: proof.proof,
622
+ }),
623
+ tokenProgram: initArgs.tokenProgram,
624
+ tokenAccount: derived.address,
625
+ mint: initArgs.mint,
626
+ owner: initArgs.authority,
627
+ },
628
+ });
629
+ }
630
+
631
+ function withClobProgram(plan: ClobInstructionPlan): ClobTransactionPlan {
632
+ return { ...plan, programAddress: clobProgramAddress };
633
+ }
634
+
635
+ return {
636
+ getAccountSnapshot,
637
+ getWithdrawalCapacity,
638
+ prepareDeposit,
639
+ prepareWithdrawal,
640
+ prepareOrder,
641
+ };
642
+ }
643
+
644
+ function uniqueMarketAssets(markets: ClobTradingMarket[]): Array<{
645
+ mint: string;
646
+ tokenProgram: string;
647
+ }> {
648
+ const assets = new Map<string, { mint: string; tokenProgram: string }>();
649
+ for (const market of markets) {
650
+ for (const mint of [market.baseMint, market.quoteMint]) {
651
+ if (!mint) continue;
652
+ assets.set(assetKey(mint, market.tokenProgram), { mint, tokenProgram: market.tokenProgram });
653
+ }
654
+ }
655
+ return [...assets.values()].sort((a, b) =>
656
+ compareText(a.mint, b.mint) || compareText(a.tokenProgram, b.tokenProgram)
657
+ );
658
+ }
659
+
660
+ function uniqueSnapshotAssets(
661
+ markets: ClobTradingMarket[],
662
+ allocations: ClobAssetBalanceAllocation[],
663
+ authority: string
664
+ ): Array<{ mint: string; tokenProgram: string }> {
665
+ const assets = new Map(
666
+ uniqueMarketAssets(markets).map((asset) => [
667
+ assetKey(asset.mint, asset.tokenProgram),
668
+ asset,
669
+ ])
670
+ );
671
+ for (const allocation of allocations) {
672
+ if (allocation.authority !== authority || !allocation.metadataReady || !allocation.mint) {
673
+ continue;
674
+ }
675
+ assets.set(assetKey(allocation.mint, allocation.tokenProgram), {
676
+ mint: allocation.mint,
677
+ tokenProgram: allocation.tokenProgram,
678
+ });
679
+ }
680
+ return [...assets.values()].sort((a, b) =>
681
+ compareText(a.mint, b.mint) || compareText(a.tokenProgram, b.tokenProgram)
682
+ );
683
+ }
684
+
685
+ function marketsForAsset(
686
+ markets: ClobTradingMarket[],
687
+ mint: string,
688
+ tokenProgram: string
689
+ ): ClobTradingMarket[] {
690
+ return markets.filter((market) =>
691
+ market.tokenProgram === tokenProgram
692
+ && (market.baseMint === mint || market.quoteMint === mint)
693
+ );
694
+ }
695
+
696
+ function chooseDepositMarket(
697
+ markets: ClobTradingMarket[],
698
+ allocations: ClobAssetBalanceAllocation[],
699
+ authority: string,
700
+ mint: string
701
+ ): ClobTradingMarket {
702
+ const existingMarkets = new Set(allocations
703
+ .filter((allocation) => allocation.authority === authority
704
+ && allocation.mint === mint
705
+ && allocation.metadataReady)
706
+ .map((allocation) => allocation.market));
707
+ return markets.slice().sort((a, b) =>
708
+ Number(existingMarkets.has(b.address)) - Number(existingMarkets.has(a.address))
709
+ || compareText(a.address, b.address)
710
+ )[0]!;
711
+ }
712
+
713
+ function withdrawalAllocations(
714
+ allocations: ClobAssetBalanceAllocation[],
715
+ markets: ClobTradingMarket[],
716
+ authority: string,
717
+ mint: string,
718
+ tokenProgram: string
719
+ ): ClobAssetBalanceAllocation[] {
720
+ const marketAddresses = new Set(markets.map((market) => market.address));
721
+ const compatible = allocations.filter((allocation) =>
722
+ allocation.authority === authority
723
+ && allocation.mint === mint
724
+ && allocation.tokenProgram === tokenProgram
725
+ && allocation.metadataReady
726
+ && allocation.freeAmount > 0n
727
+ && !(allocation.statusFlags & CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN)
728
+ && marketAddresses.has(allocation.market)
729
+ );
730
+ if (compatible.length === 0 && marketsForAsset(markets, mint, tokenProgram).length === 0) {
731
+ throw assetNotFound(mint);
732
+ }
733
+ return compatible;
734
+ }
735
+
736
+ async function freshWithdrawalAllocations(
737
+ allocations: ClobAssetBalanceAllocation[],
738
+ markets: ClobTradingMarket[],
739
+ authority: string,
740
+ readSeats: (market: ClobTradingMarket) => Promise<ClobSeatEntry[]>
741
+ ): Promise<Array<{ allocation: ClobAssetBalanceAllocation; amount: bigint }>> {
742
+ const seatsByMarket = new Map<string, ClobSeatEntry[]>();
743
+ await Promise.all([...new Set(allocations.map((allocation) => allocation.market))]
744
+ .map(async (address) => {
745
+ const market = marketByAddress(markets, address);
746
+ seatsByMarket.set(address, await readSeats(market));
747
+ }));
748
+ return allocations.flatMap((allocation) => {
749
+ const seat = seatsByMarket.get(allocation.market)?.find((candidate) =>
750
+ candidate.seatIndex === allocation.seatIndex
751
+ && candidate.seatAuthority === authority
752
+ );
753
+ if (!seat) return [];
754
+ return [{
755
+ allocation,
756
+ amount: allocation.tokenSide === 'base' ? seat.quantityBase : seat.quantityQuote,
757
+ }];
758
+ }).filter((candidate) => candidate.amount > 0n);
759
+ }
760
+
761
+ function tokenSideForMint(market: ClobTradingMarket, mint: string): ClobTokenSide {
762
+ const isBase = market.baseMint === mint;
763
+ const isQuote = market.quoteMint === mint;
764
+ if (isBase === isQuote) {
765
+ throw new ClobExchangeClientError(
766
+ isBase ? 'ambiguous_asset' : 'asset_not_found',
767
+ isBase
768
+ ? 'market uses the same mint for both token sides'
769
+ : 'asset is not present in the selected market',
770
+ { market: market.address, mint }
771
+ );
772
+ }
773
+ return isBase ? 'base' : 'quote';
774
+ }
775
+
776
+ function marketByAddress(markets: ClobTradingMarket[], address: string): ClobTradingMarket {
777
+ const market = markets.find((candidate) => candidate.address === address);
778
+ if (!market) {
779
+ throw new ClobExchangeClientError(
780
+ 'incomplete_market_metadata',
781
+ 'market metadata is unavailable',
782
+ { market: address }
783
+ );
784
+ }
785
+ return market;
786
+ }
787
+
788
+ function validateMarketMetadata(market: ClobTradingMarket): void {
789
+ if (!market.address || !market.orderArena || !market.bidsCbook || !market.asksCbook
790
+ || !market.tokenProgram || !market.baseMint || !market.quoteMint
791
+ || !market.baseVault || !market.quoteVault || !market.marketAuthority) {
792
+ throw new ClobExchangeClientError(
793
+ 'incomplete_market_metadata',
794
+ 'market metadata is incomplete',
795
+ { market: market.address || '<unknown>' }
796
+ );
797
+ }
798
+ }
799
+
800
+ function transferEffects(
801
+ mint: string,
802
+ tokenProgram: string,
803
+ amount: bigint,
804
+ market: string,
805
+ from: 'wallet' | 'exchange'
806
+ ): ClobBalanceEffect[] {
807
+ const to = from === 'wallet' ? 'exchange' : 'wallet';
808
+ return [
809
+ { location: from, mint, tokenProgram, delta: -amount, ...(from === 'exchange' ? { market } : {}) },
810
+ { location: to, mint, tokenProgram, delta: amount, ...(to === 'exchange' ? { market } : {}) },
811
+ ];
812
+ }
813
+
814
+ function assetNotFound(mint: string): ClobExchangeClientError {
815
+ return new ClobExchangeClientError(
816
+ 'asset_not_found',
817
+ 'asset is not available in any CLOB market',
818
+ { mint }
819
+ );
820
+ }
821
+
822
+ function assertTargetMarketAvailable(
823
+ unavailableMarkets: ClobUnavailableMarket[],
824
+ targetMarket: string
825
+ ): void {
826
+ const unavailable = unavailableMarkets.find((entry) => entry.market === targetMarket);
827
+ if (!unavailable) return;
828
+ throw new ClobExchangeClientError(
829
+ 'incomplete_market_metadata',
830
+ 'target market metadata is unavailable',
831
+ { market: targetMarket, cause: unavailable.reason }
832
+ );
833
+ }
834
+
835
+ function isAssetDiscoveryComplete(
836
+ unavailableMarkets: ClobUnavailableMarket[],
837
+ allocations: ClobAssetBalanceAllocation[],
838
+ mint: string
839
+ ): boolean {
840
+ const allocationMarkets = new Set(allocations.map((allocation) => allocation.market));
841
+ return !unavailableMarkets.some((entry) =>
842
+ !entry.baseMint
843
+ || !entry.quoteMint
844
+ || entry.baseMint === mint
845
+ || entry.quoteMint === mint
846
+ || allocationMarkets.has(entry.market)
847
+ );
848
+ }
849
+
850
+ function assertAssetDiscoveryComplete(
851
+ unavailableMarkets: ClobUnavailableMarket[],
852
+ allocations: ClobAssetBalanceAllocation[],
853
+ authority: string,
854
+ mint: string,
855
+ ignoredMarket?: string
856
+ ): void {
857
+ const allocationMarkets = new Set(allocations
858
+ .filter((allocation) => allocation.authority === authority && allocation.mint === mint)
859
+ .map((allocation) => allocation.market));
860
+ const relevant = unavailableMarkets.filter((entry) =>
861
+ entry.market !== ignoredMarket
862
+ && (
863
+ !entry.baseMint
864
+ || !entry.quoteMint
865
+ || entry.baseMint === mint
866
+ || entry.quoteMint === mint
867
+ || allocationMarkets.has(entry.market)
868
+ )
869
+ );
870
+ if (relevant.length > 0) throw incompleteDiscovery(relevant, mint);
871
+ }
872
+
873
+ function incompleteDiscovery(
874
+ unavailableMarkets: ClobUnavailableMarket[],
875
+ mint?: string
876
+ ): ClobExchangeClientError {
877
+ return new ClobExchangeClientError(
878
+ 'data_source_unavailable',
879
+ 'CLOB market discovery is incomplete',
880
+ {
881
+ unavailableMarkets: unavailableMarkets.map((entry) => entry.market).join(','),
882
+ ...(mint ? { mint } : {}),
883
+ }
884
+ );
885
+ }
886
+
887
+ function assertPositiveAmount(amount: bigint): void {
888
+ if (amount <= 0n || amount > 0xffffffffffffffffn) {
889
+ throw new ClobExchangeClientError(
890
+ 'invalid_amount',
891
+ 'amount must be between 1 and 18446744073709551615'
892
+ );
893
+ }
894
+ }
895
+
896
+ function sortMarkets(markets: ClobTradingMarket[]): ClobTradingMarket[] {
897
+ return markets.slice().sort((a, b) => compareText(a.address, b.address));
898
+ }
899
+
900
+ function assetKey(mint: string, tokenProgram: string): string {
901
+ return mint + '\u0000' + tokenProgram;
902
+ }
903
+
904
+ function compareText(a: string, b: string): number {
905
+ return a < b ? -1 : a > b ? 1 : 0;
906
+ }
907
+
908
+ function compareBigInt(a: bigint, b: bigint): number {
909
+ return a < b ? -1 : a > b ? 1 : 0;
910
+ }
911
+
912
+ function errorMessage(error: unknown): string {
913
+ return error instanceof Error ? error.message : String(error);
914
+ }