@thru/programs 0.3.3 → 0.3.5

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