@thru/programs 0.2.39 → 0.3.1

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,939 @@
1
+ import { Pubkey } from '@thru/sdk';
2
+ import { MULTICALL_PROGRAM_ADDRESS, buildMulticallInstruction } from '../multicall';
3
+ import {
4
+ CLOB_STATUS_FLAG_DEPOSITS_FROZEN,
5
+ CLOB_STATUS_FLAG_PAUSED,
6
+ CLOB_STATUS_FLAG_POST_ONLY,
7
+ CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN,
8
+ assertClobActiveSeatIndex,
9
+ createMarketRecordInstruction,
10
+ createOrderEntryInstruction,
11
+ createSeatCreateInstruction,
12
+ createTokenDepositInstruction,
13
+ createTokenWithdrawInstruction,
14
+ } from './index';
15
+ import type {
16
+ ClobOrderSide,
17
+ ClobOrderType,
18
+ ClobSeatEntry,
19
+ ClobTokenSide,
20
+ InstructionData,
21
+ } from './index';
22
+
23
+ /* Exchange-facing helpers keep market seats as an implementation detail.
24
+ Indexed allocations are used to discover funds; callers re-read the
25
+ selected seats from chain before submitting a prepared plan. */
26
+
27
+ export interface ClobAssetBalanceAllocation {
28
+ market: string;
29
+ authority: string;
30
+ seatIndex: number;
31
+ tokenSide: ClobTokenSide;
32
+ mint: string | null;
33
+ vault: string;
34
+ freeAmount: bigint;
35
+ statusFlags: number;
36
+ tokenProgram: string;
37
+ metadataReady: boolean;
38
+ }
39
+
40
+ export interface ClobExchangeAssetBalance {
41
+ authority: string;
42
+ mint: string;
43
+ tokenProgram: string;
44
+ freeAmount: bigint;
45
+ transferableAmount: bigint;
46
+ allocations: ClobAssetBalanceAllocation[];
47
+ }
48
+
49
+ export interface ClobTradingMarket {
50
+ address: string;
51
+ orderArena: string;
52
+ bidsCbook: string;
53
+ asksCbook: string;
54
+ tokenProgram: string;
55
+ baseMint: string | null;
56
+ quoteMint: string | null;
57
+ baseVault: string;
58
+ quoteVault: string;
59
+ marketAuthority: string;
60
+ statusFlags: number;
61
+ }
62
+
63
+ export interface ClobFundingSource {
64
+ allocation: ClobAssetBalanceAllocation;
65
+ amount: bigint;
66
+ }
67
+
68
+ /* Keep enough headroom inside the 32 KiB transaction MTU for wallet/session
69
+ wrapping and target-market accounts. The CLOB program's market-record
70
+ table allows more records, but a single signed transaction is the
71
+ practical limit.
72
+
73
+ TODO: Add multi-layer consolidation so balances fragmented across more
74
+ than this many source markets can be consolidated in bounded stages
75
+ before placing the final order. */
76
+ export const CLOB_MAX_ATOMIC_FUNDING_SOURCES = 64;
77
+
78
+ export interface ClobOrderFundingPlan {
79
+ authority: string;
80
+ targetMarket: string;
81
+ targetTokenSide: ClobTokenSide;
82
+ targetSeatIndex: number | null;
83
+ mint: string;
84
+ tokenProgram: string;
85
+ requiredAmount: bigint;
86
+ targetAmount: bigint;
87
+ exchangeAvailableAmount: bigint;
88
+ sources: ClobFundingSource[];
89
+ shortfall: bigint;
90
+ }
91
+
92
+ export interface PlanClobOrderFundingArgs {
93
+ authority: string;
94
+ targetMarket: ClobTradingMarket;
95
+ side: ClobOrderSide;
96
+ orderType?: ClobOrderType;
97
+ price: bigint;
98
+ quantity: bigint;
99
+ allocations: ClobAssetBalanceAllocation[];
100
+ targetSeatIndex?: number;
101
+ }
102
+
103
+ export interface ClobInstructionPlanReview {
104
+ instruction: 'exchange_deposit' | 'exchange_withdrawal' | 'funded_order';
105
+ label: string;
106
+ value: Record<string, string>;
107
+ }
108
+
109
+ export interface ClobInstructionPlan {
110
+ instructionData: InstructionData;
111
+ readWriteAccounts: string[];
112
+ readOnlyAccounts: string[];
113
+ review: ClobInstructionPlanReview;
114
+ }
115
+
116
+ export interface ClobTransactionPlan extends ClobInstructionPlan {
117
+ programAddress: string;
118
+ }
119
+
120
+ export interface ClobTokenAccountInitialization {
121
+ instructionData: InstructionData;
122
+ tokenProgram: string;
123
+ tokenAccount: string;
124
+ mint: string;
125
+ owner: string;
126
+ }
127
+
128
+ export interface WrapClobPlanWithTokenAccountInitializationArgs {
129
+ plan: ClobInstructionPlan;
130
+ clobProgram: string;
131
+ initialization: ClobTokenAccountInitialization;
132
+ }
133
+
134
+ export interface BuildClobExchangeDepositArgs {
135
+ market: ClobTradingMarket;
136
+ authority: string;
137
+ walletTokenAccount: string;
138
+ tokenSide: ClobTokenSide;
139
+ amount: bigint;
140
+ seatIndex: number | null;
141
+ }
142
+
143
+ export interface BuildClobExchangeWithdrawalArgs {
144
+ market: ClobTradingMarket;
145
+ authority: string;
146
+ walletTokenAccount: string;
147
+ tokenSide: ClobTokenSide;
148
+ amount: bigint;
149
+ seatIndex: number;
150
+ }
151
+
152
+ export interface BuildClobFundedOrderArgs {
153
+ plan: ClobOrderFundingPlan;
154
+ targetMarket: ClobTradingMarket;
155
+ sourceMarkets?: ClobTradingMarket[];
156
+ walletTokenAccount: string;
157
+ price: bigint;
158
+ quantity: bigint;
159
+ orderType?: ClobOrderType;
160
+ expirationTime: bigint;
161
+ clientId?: Uint8Array;
162
+ discardAfterMatch?: boolean;
163
+ failIfOutsideBook?: boolean;
164
+ }
165
+
166
+ export type ClobExchangeErrorCode =
167
+ | 'invalid_funding_amount'
168
+ | 'market_paused'
169
+ | 'market_post_only'
170
+ | 'deposits_frozen'
171
+ | 'withdrawals_frozen'
172
+ | 'insufficient_funds'
173
+ | 'too_many_funding_sources'
174
+ | 'stale_balance'
175
+ | 'funding_plan_mismatch';
176
+
177
+ export class ClobExchangeError extends Error {
178
+ readonly code: ClobExchangeErrorCode;
179
+
180
+ constructor(code: ClobExchangeErrorCode, message: string) {
181
+ super(message);
182
+ this.name = 'ClobExchangeError';
183
+ this.code = code;
184
+ }
185
+ }
186
+
187
+ /* aggregateClobExchangeBalances groups physical market seats into the
188
+ exchange-level asset balances presented to applications. */
189
+
190
+ export function aggregateClobExchangeBalances(
191
+ allocations: ClobAssetBalanceAllocation[]
192
+ ): ClobExchangeAssetBalance[] {
193
+ const groups = new Map<string, ClobExchangeAssetBalance>();
194
+ for (const allocation of allocations) {
195
+ validateAllocation(allocation);
196
+ if (!allocation.metadataReady || !allocation.mint || allocation.freeAmount === 0n) continue;
197
+ const key = allocation.authority + '\u0000' + allocation.mint + '\u0000' + allocation.tokenProgram;
198
+ let balance = groups.get(key);
199
+ if (!balance) {
200
+ balance = {
201
+ authority: allocation.authority,
202
+ mint: allocation.mint,
203
+ tokenProgram: allocation.tokenProgram,
204
+ freeAmount: 0n,
205
+ transferableAmount: 0n,
206
+ allocations: [],
207
+ };
208
+ groups.set(key, balance);
209
+ }
210
+ balance.freeAmount += allocation.freeAmount;
211
+ if (!(allocation.statusFlags & CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN)) {
212
+ balance.transferableAmount += allocation.freeAmount;
213
+ }
214
+ balance.allocations.push(allocation);
215
+ }
216
+
217
+ return [...groups.values()]
218
+ .map((balance) => ({
219
+ ...balance,
220
+ allocations: balance.allocations.slice().sort(compareAllocationIdentity),
221
+ }))
222
+ .sort((a, b) => compareText(a.mint, b.mint) || compareText(a.tokenProgram, b.tokenProgram));
223
+ }
224
+
225
+ /* calculateClobOrderFundingAmount mirrors the CLOB's conservative maximum
226
+ funding requirement. A buy can spend at most price * quantity quote
227
+ units, while a sell can spend at most quantity base units. */
228
+
229
+ export function calculateClobOrderFundingAmount(args: {
230
+ side: ClobOrderSide;
231
+ price: bigint;
232
+ quantity: bigint;
233
+ }): bigint {
234
+ assertPositiveU64(args.price, 'price');
235
+ assertPositiveU64(args.quantity, 'quantity');
236
+ const amount = args.side === 'buy' ? args.price * args.quantity : args.quantity;
237
+ if (amount > 0xffffffffffffffffn) {
238
+ throw new ClobExchangeError(
239
+ 'invalid_funding_amount',
240
+ 'order funding amount exceeds the CLOB u64 balance range'
241
+ );
242
+ }
243
+ return amount;
244
+ }
245
+
246
+ /* planClobOrderFunding uses only funds that the user has explicitly
247
+ deposited into the exchange. It prioritizes the target seat and then
248
+ compatible free allocations in their existing input order. Wallet
249
+ deposits are a separate, explicit operation. */
250
+
251
+ export function planClobOrderFunding(args: PlanClobOrderFundingArgs): ClobOrderFundingPlan {
252
+ assertMarketCanTrade(args.targetMarket, args.orderType ?? 'gtc');
253
+
254
+ const targetTokenSide: ClobTokenSide = args.side === 'buy' ? 'quote' : 'base';
255
+ const mint = targetTokenSide === 'base'
256
+ ? args.targetMarket.baseMint
257
+ : args.targetMarket.quoteMint;
258
+ if (!mint) {
259
+ throw new ClobExchangeError(
260
+ 'funding_plan_mismatch',
261
+ 'target market is missing ' + targetTokenSide + ' mint metadata'
262
+ );
263
+ }
264
+
265
+ const requiredAmount = calculateClobOrderFundingAmount(args);
266
+ const compatible = args.allocations.filter((allocation) => {
267
+ validateAllocation(allocation);
268
+ return allocation.authority === args.authority
269
+ && allocation.metadataReady
270
+ && allocation.mint === mint
271
+ && allocation.tokenProgram === args.targetMarket.tokenProgram;
272
+ });
273
+ assertUniqueAllocationIdentities(compatible);
274
+ const targetAllocations = compatible
275
+ .filter((allocation) => allocation.market === args.targetMarket.address
276
+ && allocation.tokenSide === targetTokenSide
277
+ && allocation.vault === vaultForSide(args.targetMarket, targetTokenSide))
278
+ .sort(compareTargetAllocation);
279
+ const target = args.targetSeatIndex === undefined
280
+ ? targetAllocations[0] ?? null
281
+ : targetAllocations.find((allocation) => allocation.seatIndex === args.targetSeatIndex) ?? null;
282
+ if (args.targetSeatIndex !== undefined && !target) {
283
+ throw new ClobExchangeError(
284
+ 'funding_plan_mismatch',
285
+ 'requested target seat is not present in the indexed allocations'
286
+ );
287
+ }
288
+
289
+ const targetAmount = minBigInt(requiredAmount, target?.freeAmount ?? 0n);
290
+ let remaining = requiredAmount - targetAmount;
291
+ const targetAllocationIdentity = target ? sourceAllocationIdentity(target) : null;
292
+ const sourceCandidates = compatible.filter((allocation) =>
293
+ sourceAllocationIdentity(allocation) !== targetAllocationIdentity
294
+ && allocation.freeAmount > 0n
295
+ && !(allocation.statusFlags & CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN)
296
+ );
297
+ const sources: ClobFundingSource[] = [];
298
+ for (const allocation of sourceCandidates) {
299
+ if (remaining === 0n) break;
300
+ if (sources.length >= CLOB_MAX_ATOMIC_FUNDING_SOURCES) {
301
+ throw new ClobExchangeError(
302
+ 'too_many_funding_sources',
303
+ 'exchange balance is fragmented across more than '
304
+ + CLOB_MAX_ATOMIC_FUNDING_SOURCES.toString()
305
+ + ' source allocations for one atomic order'
306
+ );
307
+ }
308
+ const amount = minBigInt(remaining, allocation.freeAmount);
309
+ sources.push({ allocation, amount });
310
+ remaining -= amount;
311
+ }
312
+
313
+ if (requiredAmount > targetAmount
314
+ && args.targetMarket.statusFlags & CLOB_STATUS_FLAG_DEPOSITS_FROZEN) {
315
+ throw new ClobExchangeError(
316
+ 'deposits_frozen',
317
+ 'target market deposits are frozen and its existing allocation cannot fund the order'
318
+ );
319
+ }
320
+
321
+ return {
322
+ authority: args.authority,
323
+ targetMarket: args.targetMarket.address,
324
+ targetTokenSide,
325
+ targetSeatIndex: target?.seatIndex ?? null,
326
+ mint,
327
+ tokenProgram: args.targetMarket.tokenProgram,
328
+ requiredAmount,
329
+ targetAmount,
330
+ exchangeAvailableAmount: (target?.freeAmount ?? 0n) + sourceCandidates.reduce(
331
+ (sum, allocation) => sum + allocation.freeAmount,
332
+ 0n
333
+ ),
334
+ sources,
335
+ shortfall: remaining,
336
+ };
337
+ }
338
+
339
+ /* validateClobOrderFundingPlanSeats checks indexed selections against fresh
340
+ seat-arena reads immediately before transaction construction. Missing
341
+ source-market reads are a caller mismatch; only supplied state that no
342
+ longer matches the plan is classified as stale. */
343
+
344
+ export function validateClobOrderFundingPlanSeats(args: {
345
+ plan: ClobOrderFundingPlan;
346
+ targetSeats: ClobSeatEntry[];
347
+ sourceSeatsByMarket?: Readonly<Record<string, ClobSeatEntry[]>>;
348
+ }): void {
349
+ if (args.plan.targetSeatIndex === null) {
350
+ if (args.targetSeats.some((seat) => seat.seatAuthority === args.plan.authority)) {
351
+ throw new ClobExchangeError('stale_balance', 'a target seat appeared after funding was planned');
352
+ }
353
+ } else {
354
+ const seat = args.targetSeats.find((entry) =>
355
+ entry.seatIndex === args.plan.targetSeatIndex
356
+ && entry.seatAuthority === args.plan.authority
357
+ );
358
+ const currentAmount = seat ? seatAmount(seat, args.plan.targetTokenSide) : null;
359
+ if (currentAmount === null
360
+ || currentAmount < args.plan.targetAmount
361
+ || (args.plan.sources.length > 0 && currentAmount !== args.plan.targetAmount)) {
362
+ throw new ClobExchangeError('stale_balance', 'target seat balance changed after funding was planned');
363
+ }
364
+ }
365
+
366
+ const hasExternalSources = args.plan.sources.some(
367
+ (source) => source.allocation.market !== args.plan.targetMarket
368
+ );
369
+ if (hasExternalSources && !args.sourceSeatsByMarket) {
370
+ throw new ClobExchangeError(
371
+ 'funding_plan_mismatch',
372
+ 'fresh source seat data is required for every planned funding market'
373
+ );
374
+ }
375
+ for (const source of args.plan.sources) {
376
+ const isTargetMarketSource = source.allocation.market === args.plan.targetMarket;
377
+ if (!isTargetMarketSource
378
+ && !Object.prototype.hasOwnProperty.call(args.sourceSeatsByMarket, source.allocation.market)) {
379
+ throw new ClobExchangeError(
380
+ 'funding_plan_mismatch',
381
+ 'fresh source seat data is missing for market ' + source.allocation.market
382
+ );
383
+ }
384
+ const sourceSeats = isTargetMarketSource
385
+ ? args.targetSeats
386
+ : args.sourceSeatsByMarket![source.allocation.market];
387
+ const seat = sourceSeats.find((entry) =>
388
+ entry.seatIndex === source.allocation.seatIndex
389
+ && entry.seatAuthority === args.plan.authority
390
+ );
391
+ if (!seat || seatAmount(seat, source.allocation.tokenSide) < source.amount) {
392
+ throw new ClobExchangeError(
393
+ 'stale_balance',
394
+ 'source seat balance changed after funding was planned for market '
395
+ + source.allocation.market
396
+ );
397
+ }
398
+ }
399
+ }
400
+
401
+ /* buildClobExchangeDepositInstructionPlan prepares an unsigned deposit into
402
+ the exchange abstraction, creating the selected market seat if needed. */
403
+
404
+ export function buildClobExchangeDepositInstructionPlan(
405
+ args: BuildClobExchangeDepositArgs
406
+ ): ClobInstructionPlan {
407
+ assertPositiveU64(args.amount, 'amount');
408
+ if (args.market.statusFlags & CLOB_STATUS_FLAG_DEPOSITS_FROZEN) {
409
+ throw new ClobExchangeError('deposits_frozen', 'market deposits are frozen');
410
+ }
411
+ const marketRecordIndex = 1;
412
+ const opensSeat = args.seatIndex === null;
413
+ const instructions = [
414
+ marketRecordInstruction(args.market, marketRecordIndex, opensSeat ? null : args.authority, args.seatIndex),
415
+ ...(opensSeat
416
+ ? [createSeatCreateInstruction({
417
+ marketRecordIndex,
418
+ seatAuthorityAccountBytes: addressBytes(args.authority),
419
+ })]
420
+ : []),
421
+ createTokenDepositInstruction({
422
+ marketRecordIndex,
423
+ tokenProgramAccountBytes: addressBytes(args.market.tokenProgram),
424
+ fromAccountBytes: addressBytes(args.walletTokenAccount),
425
+ toAccountBytes: addressBytes(vaultForSide(args.market, args.tokenSide)),
426
+ amount: args.amount,
427
+ }),
428
+ ];
429
+ const accounts = new AccountPlan();
430
+ addTargetMarketAccounts(accounts, args.market);
431
+ accounts.addWrite(args.walletTokenAccount);
432
+ accounts.addWrite(vaultForSide(args.market, args.tokenSide));
433
+ accounts.addRead(args.authority);
434
+ accounts.addRead(args.market.tokenProgram);
435
+ return accounts.finish(concatClobInstructions(...instructions), {
436
+ instruction: 'exchange_deposit',
437
+ label: 'Deposit to CLOB exchange',
438
+ value: {
439
+ market: args.market.address,
440
+ mint: mintForSide(args.market, args.tokenSide),
441
+ amount: args.amount.toString(),
442
+ },
443
+ });
444
+ }
445
+
446
+ /* buildClobExchangeWithdrawalInstructionPlan prepares an unsigned exchange
447
+ withdrawal from an exact indexed allocation. */
448
+
449
+ export function buildClobExchangeWithdrawalInstructionPlan(
450
+ args: BuildClobExchangeWithdrawalArgs
451
+ ): ClobInstructionPlan {
452
+ assertPositiveU64(args.amount, 'amount');
453
+ if (args.market.statusFlags & CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN) {
454
+ throw new ClobExchangeError('withdrawals_frozen', 'market withdrawals are frozen');
455
+ }
456
+ const marketRecordIndex = 1;
457
+ const vault = vaultForSide(args.market, args.tokenSide);
458
+ const instructionData = concatClobInstructions(
459
+ marketRecordInstruction(args.market, marketRecordIndex, args.authority, args.seatIndex),
460
+ createTokenWithdrawInstruction({
461
+ marketRecordIndex,
462
+ tokenProgramAccountBytes: addressBytes(args.market.tokenProgram),
463
+ fromAccountBytes: addressBytes(vault),
464
+ toAccountBytes: addressBytes(args.walletTokenAccount),
465
+ amount: args.amount,
466
+ })
467
+ );
468
+ const accounts = new AccountPlan();
469
+ addSourceMarketAccounts(accounts, args.market, vault);
470
+ accounts.addWrite(args.walletTokenAccount);
471
+ accounts.addRead(args.authority);
472
+ accounts.addRead(args.market.tokenProgram);
473
+ return accounts.finish(instructionData, {
474
+ instruction: 'exchange_withdrawal',
475
+ label: 'Withdraw from CLOB exchange',
476
+ value: {
477
+ market: args.market.address,
478
+ mint: mintForSide(args.market, args.tokenSide),
479
+ amount: args.amount.toString(),
480
+ },
481
+ });
482
+ }
483
+
484
+ /* buildClobFundedOrderInstructionPlan combines internal exchange
485
+ rebalances from every planned source and the target order in one CLOB
486
+ program invocation. It never consumes funds that have not already been
487
+ deposited into the exchange. */
488
+
489
+ export function buildClobFundedOrderInstructionPlan(
490
+ args: BuildClobFundedOrderArgs
491
+ ): ClobInstructionPlan {
492
+ validateFundedOrderPlan(args);
493
+ const instructions: InstructionData[] = [];
494
+ const accounts = new AccountPlan();
495
+ const sourceMarkets = indexSourceMarkets(args.sourceMarkets ?? []);
496
+
497
+ args.plan.sources.forEach((source, index) => {
498
+ const sourceMarket = source.allocation.market === args.targetMarket.address
499
+ ? args.targetMarket
500
+ : sourceMarkets.get(source.allocation.market)!;
501
+ const sourceRecordIndex = index + 1;
502
+ instructions.push(
503
+ marketRecordInstruction(
504
+ sourceMarket,
505
+ sourceRecordIndex,
506
+ args.plan.authority,
507
+ source.allocation.seatIndex
508
+ ),
509
+ createTokenWithdrawInstruction({
510
+ marketRecordIndex: sourceRecordIndex,
511
+ tokenProgramAccountBytes: addressBytes(args.plan.tokenProgram),
512
+ fromAccountBytes: addressBytes(source.allocation.vault),
513
+ toAccountBytes: addressBytes(args.walletTokenAccount),
514
+ amount: source.amount,
515
+ })
516
+ );
517
+ addSourceMarketAccounts(accounts, sourceMarket, source.allocation.vault);
518
+ });
519
+
520
+ const targetRecordIndex = args.plan.sources.length + 1;
521
+ const opensSeat = args.plan.targetSeatIndex === null;
522
+ instructions.push(
523
+ marketRecordInstruction(
524
+ args.targetMarket,
525
+ targetRecordIndex,
526
+ opensSeat ? null : args.plan.authority,
527
+ args.plan.targetSeatIndex
528
+ )
529
+ );
530
+ if (opensSeat) {
531
+ instructions.push(createSeatCreateInstruction({
532
+ marketRecordIndex: targetRecordIndex,
533
+ seatAuthorityAccountBytes: addressBytes(args.plan.authority),
534
+ }));
535
+ }
536
+
537
+ const sourceAmount = fundingSourcesAmount(args.plan.sources);
538
+ if (sourceAmount > 0n) {
539
+ instructions.push(createTokenDepositInstruction({
540
+ marketRecordIndex: targetRecordIndex,
541
+ tokenProgramAccountBytes: addressBytes(args.plan.tokenProgram),
542
+ fromAccountBytes: addressBytes(args.walletTokenAccount),
543
+ toAccountBytes: addressBytes(vaultForSide(args.targetMarket, args.plan.targetTokenSide)),
544
+ amount: sourceAmount,
545
+ }));
546
+ accounts.addWrite(args.walletTokenAccount);
547
+ accounts.addWrite(vaultForSide(args.targetMarket, args.plan.targetTokenSide));
548
+ }
549
+
550
+ instructions.push(createOrderEntryInstruction({
551
+ marketRecordIndex: targetRecordIndex,
552
+ side: args.plan.targetTokenSide === 'quote' ? 'buy' : 'sell',
553
+ orderType: args.orderType,
554
+ price: args.price,
555
+ quantity: args.quantity,
556
+ expirationTime: args.expirationTime,
557
+ clientId: args.clientId,
558
+ discardAfterMatch: args.discardAfterMatch,
559
+ failIfOutsideBook: args.failIfOutsideBook,
560
+ }));
561
+ addTargetMarketAccounts(accounts, args.targetMarket);
562
+ accounts.addRead(args.plan.authority);
563
+ accounts.addRead(args.plan.tokenProgram);
564
+
565
+ return accounts.finish(concatClobInstructions(...instructions), {
566
+ instruction: 'funded_order',
567
+ label: 'Place order using CLOB exchange balance',
568
+ value: {
569
+ targetMarket: args.targetMarket.address,
570
+ mint: args.plan.mint,
571
+ requiredAmount: args.plan.requiredAmount.toString(),
572
+ exchangeAmount: (args.plan.targetAmount + sourceAmount).toString(),
573
+ sourceMarketCount: args.plan.sources.length.toString(),
574
+ ...(args.plan.sources.length > 0
575
+ ? {
576
+ sourceMarkets: args.plan.sources
577
+ .map((source) => source.allocation.market + ':' + source.amount.toString())
578
+ .join(','),
579
+ }
580
+ : {}),
581
+ },
582
+ });
583
+ }
584
+
585
+ export function concatClobInstructions(...instructions: InstructionData[]): InstructionData {
586
+ return async (context) => {
587
+ const chunks = await Promise.all(instructions.map((instruction) => instruction(context)));
588
+ const output = new Uint8Array(chunks.reduce((size, chunk) => size + chunk.length, 0));
589
+ let offset = 0;
590
+ for (const chunk of chunks) {
591
+ output.set(chunk, offset);
592
+ offset += chunk.length;
593
+ }
594
+ return output;
595
+ };
596
+ }
597
+
598
+ /* wrapClobPlanWithTokenAccountInitialization executes token-account setup
599
+ before the CLOB invocation through multicall. The caller supplies the
600
+ token instruction so state-proof acquisition stays outside this package. */
601
+
602
+ export function wrapClobPlanWithTokenAccountInitialization(
603
+ args: WrapClobPlanWithTokenAccountInitializationArgs
604
+ ): ClobTransactionPlan {
605
+ const instructionData: InstructionData = async (context) => {
606
+ const [initializeAccountData, clobData] = await Promise.all([
607
+ args.initialization.instructionData(context),
608
+ args.plan.instructionData(context),
609
+ ]);
610
+ return buildMulticallInstruction([
611
+ {
612
+ programIdx: context.getAccountIndex(addressBytes(args.initialization.tokenProgram)),
613
+ instructionData: initializeAccountData,
614
+ },
615
+ {
616
+ programIdx: context.getAccountIndex(addressBytes(args.clobProgram)),
617
+ instructionData: clobData,
618
+ },
619
+ ]);
620
+ };
621
+ const accounts = new AccountPlan();
622
+ for (const account of args.plan.readWriteAccounts) accounts.addWrite(account);
623
+ for (const account of args.plan.readOnlyAccounts) accounts.addRead(account);
624
+ accounts.addWrite(args.initialization.tokenAccount);
625
+ accounts.addRead(args.initialization.mint);
626
+ accounts.addRead(args.initialization.owner);
627
+ accounts.addRead(args.initialization.tokenProgram);
628
+ accounts.addRead(args.clobProgram);
629
+ const plan = accounts.finish(instructionData, {
630
+ ...args.plan.review,
631
+ value: {
632
+ ...args.plan.review.value,
633
+ initializesWalletTokenAccount: 'true',
634
+ },
635
+ });
636
+ return {
637
+ ...plan,
638
+ programAddress: MULTICALL_PROGRAM_ADDRESS,
639
+ };
640
+ }
641
+
642
+ function validateAllocation(allocation: ClobAssetBalanceAllocation): void {
643
+ assertU64(allocation.freeAmount, 'allocation.freeAmount');
644
+ assertClobActiveSeatIndex(allocation.seatIndex, 'allocation.seatIndex');
645
+ }
646
+
647
+ function assertMarketCanTrade(market: ClobTradingMarket, orderType: ClobOrderType): void {
648
+ if (market.statusFlags & CLOB_STATUS_FLAG_PAUSED) {
649
+ throw new ClobExchangeError('market_paused', 'target market is paused');
650
+ }
651
+ if (market.statusFlags & CLOB_STATUS_FLAG_POST_ONLY && orderType !== 'alo') {
652
+ throw new ClobExchangeError(
653
+ 'market_post_only',
654
+ 'target market is post-only and requires an ALO order'
655
+ );
656
+ }
657
+ }
658
+
659
+ function validateFundedOrderPlan(args: BuildClobFundedOrderArgs): void {
660
+ const plan = args.plan;
661
+ if (!Array.isArray(plan.sources)) {
662
+ throw new ClobExchangeError('funding_plan_mismatch', 'funding sources must be an array');
663
+ }
664
+ if (plan.sources.length > CLOB_MAX_ATOMIC_FUNDING_SOURCES) {
665
+ throw new ClobExchangeError(
666
+ 'too_many_funding_sources',
667
+ 'funding plan exceeds the atomic source allocation limit'
668
+ );
669
+ }
670
+ assertFundingPlanU64(plan.requiredAmount, 'requiredAmount');
671
+ assertFundingPlanU64(plan.targetAmount, 'targetAmount');
672
+ assertFundingPlanU64(plan.shortfall, 'shortfall');
673
+ assertUniqueAllocationIdentities(plan.sources.map((source) => source.allocation));
674
+ plan.sources.forEach((source, index) => {
675
+ validateAllocation(source.allocation);
676
+ assertFundingPlanU64(source.amount, 'sources[' + index.toString() + '].amount');
677
+ if (source.amount === 0n || source.amount > source.allocation.freeAmount) {
678
+ throw new ClobExchangeError(
679
+ 'funding_plan_mismatch',
680
+ 'funding source amount must be positive and no greater than its free allocation'
681
+ );
682
+ }
683
+ });
684
+ if (plan.shortfall > 0n) {
685
+ throw new ClobExchangeError(
686
+ 'insufficient_funds',
687
+ 'order funding plan is short ' + plan.shortfall.toString() + ' units'
688
+ );
689
+ }
690
+ assertMarketCanTrade(args.targetMarket, args.orderType ?? 'gtc');
691
+ const expectedAmount = calculateClobOrderFundingAmount({
692
+ side: plan.targetTokenSide === 'quote' ? 'buy' : 'sell',
693
+ price: args.price,
694
+ quantity: args.quantity,
695
+ });
696
+ const plannedAmount = plan.targetAmount
697
+ + fundingSourcesAmount(plan.sources);
698
+ if (plannedAmount !== plan.requiredAmount) {
699
+ throw new ClobExchangeError(
700
+ 'funding_plan_mismatch',
701
+ 'funding plan amounts do not add up to the required order funding'
702
+ );
703
+ }
704
+ if (plan.targetMarket !== args.targetMarket.address
705
+ || plan.tokenProgram !== args.targetMarket.tokenProgram
706
+ || plan.mint !== mintForSide(args.targetMarket, plan.targetTokenSide)
707
+ || plan.requiredAmount !== expectedAmount) {
708
+ throw new ClobExchangeError(
709
+ 'funding_plan_mismatch',
710
+ 'funding plan does not match the target market or order'
711
+ );
712
+ }
713
+
714
+ const sourceMarkets = indexSourceMarkets(args.sourceMarkets ?? []);
715
+ const plannedExternalSourceMarkets = new Set(
716
+ plan.sources
717
+ .map((source) => source.allocation.market)
718
+ .filter((market) => market !== args.targetMarket.address)
719
+ );
720
+ if (sourceMarkets.size !== plannedExternalSourceMarkets.size) {
721
+ throw new ClobExchangeError(
722
+ 'funding_plan_mismatch',
723
+ 'prepared source markets do not exactly match the funding plan'
724
+ );
725
+ }
726
+ for (const source of plan.sources) {
727
+ const isTargetMarketSource = source.allocation.market === args.targetMarket.address;
728
+ const sourceMarket = isTargetMarketSource
729
+ ? args.targetMarket
730
+ : sourceMarkets.get(source.allocation.market);
731
+ if (!sourceMarket
732
+ || sourceMarket.tokenProgram !== plan.tokenProgram
733
+ || source.allocation.authority !== plan.authority
734
+ || source.allocation.mint !== plan.mint
735
+ || source.allocation.tokenSide !== sideForVault(sourceMarket, source.allocation.vault)
736
+ || (isTargetMarketSource
737
+ && plan.targetSeatIndex !== null
738
+ && source.allocation.seatIndex === plan.targetSeatIndex
739
+ && source.allocation.tokenSide === plan.targetTokenSide)) {
740
+ throw new ClobExchangeError(
741
+ 'funding_plan_mismatch',
742
+ 'funding source does not match its prepared source market allocation'
743
+ );
744
+ }
745
+ if (sourceMarket.statusFlags & CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN) {
746
+ throw new ClobExchangeError('withdrawals_frozen', 'source market withdrawals are frozen');
747
+ }
748
+ }
749
+ if (plan.sources.length > 0
750
+ && args.targetMarket.statusFlags & CLOB_STATUS_FLAG_DEPOSITS_FROZEN) {
751
+ throw new ClobExchangeError('deposits_frozen', 'target market deposits are frozen');
752
+ }
753
+ }
754
+
755
+ function assertFundingPlanU64(value: bigint, label: string): void {
756
+ if (value < 0n || value > 0xffffffffffffffffn) {
757
+ throw new ClobExchangeError(
758
+ 'funding_plan_mismatch',
759
+ label + ' must be between 0 and 18446744073709551615'
760
+ );
761
+ }
762
+ }
763
+
764
+ function marketRecordInstruction(
765
+ market: ClobTradingMarket,
766
+ marketRecordIndex: number,
767
+ authority: string | null,
768
+ seatIndex: number | null
769
+ ): InstructionData {
770
+ return createMarketRecordInstruction({
771
+ marketRecordIndex,
772
+ seatArenaAccountBytes: addressBytes(market.address),
773
+ orderArenaAccountBytes: addressBytes(market.orderArena),
774
+ bidsCbookAccountBytes: addressBytes(market.bidsCbook),
775
+ asksCbookAccountBytes: addressBytes(market.asksCbook),
776
+ seatAuthorityAccountBytes: authority ? addressBytes(authority) : undefined,
777
+ seatIndex: seatIndex ?? undefined,
778
+ tokenProgramAccountBytes: addressBytes(market.tokenProgram),
779
+ baseVaultAccountBytes: addressBytes(market.baseVault),
780
+ quoteVaultAccountBytes: addressBytes(market.quoteVault),
781
+ });
782
+ }
783
+
784
+ function addTargetMarketAccounts(accounts: AccountPlan, market: ClobTradingMarket): void {
785
+ accounts.addWrite(market.address);
786
+ accounts.addWrite(market.orderArena);
787
+ accounts.addWrite(market.bidsCbook);
788
+ accounts.addWrite(market.asksCbook);
789
+ accounts.addRead(market.baseVault);
790
+ accounts.addRead(market.quoteVault);
791
+ }
792
+
793
+ function addSourceMarketAccounts(
794
+ accounts: AccountPlan,
795
+ market: ClobTradingMarket,
796
+ sourceVault: string
797
+ ): void {
798
+ accounts.addWrite(market.address);
799
+ accounts.addWrite(sourceVault);
800
+ /* The CLOB's market_record instruction currently validates all three
801
+ orderbook accounts through tsys_set_account_data_writable(), even when
802
+ the record is only used as a withdrawal source. Passing them read-only
803
+ makes that validation revert before the cross-market withdrawal. */
804
+ accounts.addWrite(market.orderArena);
805
+ accounts.addWrite(market.bidsCbook);
806
+ accounts.addWrite(market.asksCbook);
807
+ accounts.addRead(market.baseVault);
808
+ accounts.addRead(market.quoteVault);
809
+ }
810
+
811
+ class AccountPlan {
812
+ readonly writes = new Set<string>();
813
+ readonly reads = new Set<string>();
814
+
815
+ addWrite(address: string): void {
816
+ this.writes.add(address);
817
+ this.reads.delete(address);
818
+ }
819
+
820
+ addRead(address: string): void {
821
+ if (!this.writes.has(address)) this.reads.add(address);
822
+ }
823
+
824
+ finish(instructionData: InstructionData, review: ClobInstructionPlanReview): ClobInstructionPlan {
825
+ return {
826
+ instructionData,
827
+ readWriteAccounts: [...this.writes],
828
+ readOnlyAccounts: [...this.reads],
829
+ review,
830
+ };
831
+ }
832
+ }
833
+
834
+ function addressBytes(address: string): Uint8Array {
835
+ return Pubkey.from(address).toBytes();
836
+ }
837
+
838
+ function mintForSide(market: ClobTradingMarket, side: ClobTokenSide): string {
839
+ const mint = side === 'base' ? market.baseMint : market.quoteMint;
840
+ if (!mint) {
841
+ throw new ClobExchangeError(
842
+ 'funding_plan_mismatch',
843
+ 'market is missing ' + side + ' mint metadata'
844
+ );
845
+ }
846
+ return mint;
847
+ }
848
+
849
+ function vaultForSide(market: ClobTradingMarket, side: ClobTokenSide): string {
850
+ return side === 'base' ? market.baseVault : market.quoteVault;
851
+ }
852
+
853
+ function sideForVault(market: ClobTradingMarket, vault: string): ClobTokenSide | null {
854
+ if (vault === market.baseVault) return 'base';
855
+ if (vault === market.quoteVault) return 'quote';
856
+ return null;
857
+ }
858
+
859
+ function seatAmount(seat: ClobSeatEntry, side: ClobTokenSide): bigint {
860
+ return side === 'base' ? seat.quantityBase : seat.quantityQuote;
861
+ }
862
+
863
+ function compareAllocationIdentity(
864
+ a: ClobAssetBalanceAllocation,
865
+ b: ClobAssetBalanceAllocation
866
+ ): number {
867
+ return compareText(a.market, b.market)
868
+ || a.seatIndex - b.seatIndex
869
+ || compareText(a.tokenSide, b.tokenSide);
870
+ }
871
+
872
+ function compareTargetAllocation(
873
+ a: ClobAssetBalanceAllocation,
874
+ b: ClobAssetBalanceAllocation
875
+ ): number {
876
+ return compareBigIntDescending(a.freeAmount, b.freeAmount) || a.seatIndex - b.seatIndex;
877
+ }
878
+
879
+ function compareBigIntDescending(a: bigint, b: bigint): number {
880
+ return a > b ? -1 : a < b ? 1 : 0;
881
+ }
882
+
883
+ function compareText(a: string, b: string): number {
884
+ return a < b ? -1 : a > b ? 1 : 0;
885
+ }
886
+
887
+ function sourceAllocationIdentity(allocation: ClobAssetBalanceAllocation): string {
888
+ return allocation.market + '\u0000' + allocation.seatIndex.toString() + '\u0000' + allocation.tokenSide;
889
+ }
890
+
891
+ function assertUniqueAllocationIdentities(allocations: ClobAssetBalanceAllocation[]): void {
892
+ const identities = new Set<string>();
893
+ for (const allocation of allocations) {
894
+ const identity = sourceAllocationIdentity(allocation);
895
+ if (identities.has(identity)) {
896
+ throw new ClobExchangeError(
897
+ 'funding_plan_mismatch',
898
+ 'duplicate indexed allocation for market ' + allocation.market
899
+ + ' seat ' + allocation.seatIndex.toString()
900
+ );
901
+ }
902
+ identities.add(identity);
903
+ }
904
+ }
905
+
906
+ function fundingSourcesAmount(sources: ClobFundingSource[]): bigint {
907
+ return sources.reduce((amount, source) => amount + source.amount, 0n);
908
+ }
909
+
910
+ function indexSourceMarkets(markets: ClobTradingMarket[]): Map<string, ClobTradingMarket> {
911
+ const byAddress = new Map<string, ClobTradingMarket>();
912
+ for (const market of markets) {
913
+ if (byAddress.has(market.address)) {
914
+ throw new ClobExchangeError(
915
+ 'funding_plan_mismatch',
916
+ 'duplicate prepared source market ' + market.address
917
+ );
918
+ }
919
+ byAddress.set(market.address, market);
920
+ }
921
+ return byAddress;
922
+ }
923
+
924
+ function minBigInt(a: bigint, b: bigint): bigint {
925
+ return a < b ? a : b;
926
+ }
927
+
928
+ function assertPositiveU64(value: bigint, label: string): void {
929
+ assertU64(value, label);
930
+ if (value === 0n) {
931
+ throw new ClobExchangeError('invalid_funding_amount', label + ' must be positive');
932
+ }
933
+ }
934
+
935
+ function assertU64(value: bigint, label: string): void {
936
+ if (value < 0n || value > 0xffffffffffffffffn) {
937
+ throw new Error(label + ' must be between 0 and 18446744073709551615');
938
+ }
939
+ }