@thru/programs 0.3.3 → 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.
@@ -1,3 +1,4 @@
1
+ import { deriveTokenAccountAddress, parseTokenAccountData, isAccountNotFoundError, parseMintAccountData, createInitializeAccountInstruction } from '../chunk-7DRJVAYI.js';
1
2
  import { MULTICALL_PROGRAM_ADDRESS, buildMulticallInstruction } from '../chunk-J7B7XYOI.js';
2
3
  import { Pubkey as Pubkey$1 } from '@thru/sdk';
3
4
  import { encodeAddress } from '@thru/sdk/helpers';
@@ -11616,6 +11617,594 @@ function assertU64(value, label) {
11616
11617
  throw new Error(label + " must be between 0 and 18446744073709551615");
11617
11618
  }
11618
11619
  }
11620
+ var TOKEN_ACCOUNT_DEFAULT_SEED = new Uint8Array(32);
11621
+ var STATE_PROOF_TYPE_CREATING = 1;
11622
+ var DEFAULT_ORDER_EXPIRATION_TIME = 9223372036854775807n;
11623
+ var ClobExchangeClientError = class extends Error {
11624
+ constructor(code, message, details) {
11625
+ super(message);
11626
+ this.name = "ClobExchangeClientError";
11627
+ this.code = code;
11628
+ this.details = details;
11629
+ }
11630
+ };
11631
+ function createClobExchangeClient(args) {
11632
+ const clobProgramAddress = args.clobProgramAddress ?? CLOB_PROGRAM_ADDRESS;
11633
+ async function loadState(authority) {
11634
+ try {
11635
+ const [discovery, allocations] = await Promise.all([
11636
+ args.dataSource.getMarkets(),
11637
+ args.dataSource.getAssetAllocations(authority)
11638
+ ]);
11639
+ for (const market of discovery.markets) validateMarketMetadata(market);
11640
+ return {
11641
+ markets: sortMarkets(discovery.markets),
11642
+ allocations,
11643
+ unavailableMarkets: discovery.unavailableMarkets
11644
+ };
11645
+ } catch (error) {
11646
+ if (error instanceof ClobExchangeClientError) throw error;
11647
+ throw new ClobExchangeClientError(
11648
+ "data_source_unavailable",
11649
+ "CLOB exchange data source is unavailable",
11650
+ { cause: errorMessage(error) }
11651
+ );
11652
+ }
11653
+ }
11654
+ async function getAccountSnapshot(snapshotArgs) {
11655
+ const { authority } = snapshotArgs;
11656
+ const { markets, allocations, unavailableMarkets } = await loadState(authority);
11657
+ const balances = new Map(
11658
+ aggregateClobExchangeBalances(allocations).filter((balance) => balance.authority === authority).map((balance) => [assetKey(balance.mint, balance.tokenProgram), balance])
11659
+ );
11660
+ const assets = uniqueSnapshotAssets(markets, allocations, authority);
11661
+ const snapshots = await Promise.all(assets.map(async ({ mint, tokenProgram }) => {
11662
+ const balance = balances.get(assetKey(mint, tokenProgram));
11663
+ const [wallet, symbol] = await Promise.all([
11664
+ readCanonicalWalletAccount(authority, mint, tokenProgram),
11665
+ readMintSymbol(mint)
11666
+ ]);
11667
+ return {
11668
+ mint,
11669
+ tokenProgram,
11670
+ symbol,
11671
+ discoveryComplete: isAssetDiscoveryComplete(
11672
+ unavailableMarkets,
11673
+ balance?.allocations ?? [],
11674
+ mint
11675
+ ),
11676
+ exchange: {
11677
+ freeAmount: balance?.freeAmount ?? 0n,
11678
+ transferableAmount: balance?.transferableAmount ?? 0n,
11679
+ allocations: balance?.allocations ?? []
11680
+ },
11681
+ wallet
11682
+ };
11683
+ }));
11684
+ return { authority, assets: snapshots, unavailableMarkets };
11685
+ }
11686
+ async function getWithdrawalCapacity(capacityArgs) {
11687
+ const { markets, allocations, unavailableMarkets } = await loadState(capacityArgs.authority);
11688
+ assertAssetDiscoveryComplete(
11689
+ unavailableMarkets,
11690
+ allocations,
11691
+ capacityArgs.authority,
11692
+ capacityArgs.mint
11693
+ );
11694
+ const candidates = withdrawalAllocations(
11695
+ allocations,
11696
+ markets,
11697
+ capacityArgs.authority,
11698
+ capacityArgs.mint,
11699
+ args.tokenProgramAddress
11700
+ );
11701
+ const fresh = await freshWithdrawalAllocations(
11702
+ candidates,
11703
+ markets,
11704
+ capacityArgs.authority,
11705
+ readMarketSeats
11706
+ );
11707
+ return {
11708
+ mint: capacityArgs.mint,
11709
+ tokenProgram: args.tokenProgramAddress,
11710
+ total: fresh.reduce((sum, entry) => sum + entry.amount, 0n),
11711
+ maximumSingleAllocation: fresh.reduce(
11712
+ (maximum, entry) => entry.amount > maximum ? entry.amount : maximum,
11713
+ 0n
11714
+ )
11715
+ };
11716
+ }
11717
+ async function prepareDeposit(depositArgs) {
11718
+ assertPositiveAmount(depositArgs.amount);
11719
+ const { markets, allocations, unavailableMarkets } = await loadState(depositArgs.authority);
11720
+ assertAssetDiscoveryComplete(
11721
+ unavailableMarkets,
11722
+ allocations,
11723
+ depositArgs.authority,
11724
+ depositArgs.mint
11725
+ );
11726
+ const eligible = marketsForAsset(markets, depositArgs.mint, args.tokenProgramAddress);
11727
+ if (eligible.length === 0) throw assetNotFound(depositArgs.mint);
11728
+ const acceptingDeposits = eligible.filter(
11729
+ (market2) => !(market2.statusFlags & CLOB_STATUS_FLAG_DEPOSITS_FROZEN)
11730
+ );
11731
+ const market = chooseDepositMarket(
11732
+ acceptingDeposits.length > 0 ? acceptingDeposits : eligible,
11733
+ allocations,
11734
+ depositArgs.authority,
11735
+ depositArgs.mint
11736
+ );
11737
+ const tokenSide = tokenSideForMint(market, depositArgs.mint);
11738
+ const seats = await readMarketSeats(market);
11739
+ const existingSeat = seats.filter((seat) => seat.seatAuthority === depositArgs.authority).sort((a, b) => a.seatIndex - b.seatIndex)[0] ?? null;
11740
+ const wallet = await readCanonicalWalletAccount(
11741
+ depositArgs.authority,
11742
+ depositArgs.mint,
11743
+ args.tokenProgramAddress
11744
+ );
11745
+ if (wallet.amount < depositArgs.amount) {
11746
+ throw new ClobExchangeClientError(
11747
+ "insufficient_wallet_balance",
11748
+ "wallet balance is insufficient for this deposit",
11749
+ { available: wallet.amount.toString(), required: depositArgs.amount.toString() }
11750
+ );
11751
+ }
11752
+ const plan = withClobProgram(buildClobExchangeDepositInstructionPlan({
11753
+ market,
11754
+ authority: depositArgs.authority,
11755
+ walletTokenAccount: wallet.tokenAccount,
11756
+ tokenSide,
11757
+ amount: depositArgs.amount,
11758
+ seatIndex: existingSeat?.seatIndex ?? null
11759
+ }));
11760
+ return {
11761
+ plan,
11762
+ effects: transferEffects(
11763
+ depositArgs.mint,
11764
+ args.tokenProgramAddress,
11765
+ depositArgs.amount,
11766
+ market.address,
11767
+ "wallet"
11768
+ ),
11769
+ market,
11770
+ tokenSide,
11771
+ seatIndex: existingSeat?.seatIndex ?? null,
11772
+ walletTokenAccount: wallet
11773
+ };
11774
+ }
11775
+ async function prepareWithdrawal(withdrawalArgs) {
11776
+ assertPositiveAmount(withdrawalArgs.amount);
11777
+ const { markets, allocations, unavailableMarkets } = await loadState(withdrawalArgs.authority);
11778
+ assertAssetDiscoveryComplete(
11779
+ unavailableMarkets,
11780
+ allocations,
11781
+ withdrawalArgs.authority,
11782
+ withdrawalArgs.mint
11783
+ );
11784
+ const indexed = withdrawalAllocations(
11785
+ allocations,
11786
+ markets,
11787
+ withdrawalArgs.authority,
11788
+ withdrawalArgs.mint,
11789
+ args.tokenProgramAddress
11790
+ );
11791
+ const fresh = await freshWithdrawalAllocations(
11792
+ indexed,
11793
+ markets,
11794
+ withdrawalArgs.authority,
11795
+ readMarketSeats
11796
+ );
11797
+ const selected = fresh.filter((candidate) => candidate.amount >= withdrawalArgs.amount).sort((a, b) => compareBigInt(a.amount, b.amount) || compareText2(a.allocation.market, b.allocation.market) || a.allocation.seatIndex - b.allocation.seatIndex)[0];
11798
+ if (!selected) {
11799
+ const total = fresh.reduce((sum, candidate) => sum + candidate.amount, 0n);
11800
+ if (total >= withdrawalArgs.amount) {
11801
+ throw new ClobExchangeClientError(
11802
+ "fragmented_balance",
11803
+ "withdrawal amount is split across multiple market seats",
11804
+ { available: total.toString(), required: withdrawalArgs.amount.toString() }
11805
+ );
11806
+ }
11807
+ throw new ClobExchangeClientError(
11808
+ "insufficient_exchange_balance",
11809
+ "exchange balance is insufficient for this withdrawal",
11810
+ { available: total.toString(), required: withdrawalArgs.amount.toString() }
11811
+ );
11812
+ }
11813
+ const market = marketByAddress(markets, selected.allocation.market);
11814
+ const wallet = await readCanonicalWalletAccount(
11815
+ withdrawalArgs.authority,
11816
+ withdrawalArgs.mint,
11817
+ args.tokenProgramAddress
11818
+ );
11819
+ let plan = withClobProgram(buildClobExchangeWithdrawalInstructionPlan({
11820
+ market,
11821
+ authority: withdrawalArgs.authority,
11822
+ walletTokenAccount: wallet.tokenAccount,
11823
+ tokenSide: selected.allocation.tokenSide,
11824
+ amount: withdrawalArgs.amount,
11825
+ seatIndex: selected.allocation.seatIndex
11826
+ }));
11827
+ if (!wallet.exists) {
11828
+ plan = await wrapWithWalletTokenAccountInitialization({
11829
+ authority: withdrawalArgs.authority,
11830
+ mint: withdrawalArgs.mint,
11831
+ tokenProgram: args.tokenProgramAddress,
11832
+ walletTokenAccount: wallet.tokenAccount,
11833
+ plan
11834
+ });
11835
+ }
11836
+ return {
11837
+ plan,
11838
+ effects: transferEffects(
11839
+ withdrawalArgs.mint,
11840
+ args.tokenProgramAddress,
11841
+ withdrawalArgs.amount,
11842
+ market.address,
11843
+ "exchange"
11844
+ ),
11845
+ market,
11846
+ tokenSide: selected.allocation.tokenSide,
11847
+ seatIndex: selected.allocation.seatIndex,
11848
+ walletTokenAccount: wallet
11849
+ };
11850
+ }
11851
+ async function prepareOrder(orderArgs) {
11852
+ const { markets, allocations, unavailableMarkets } = await loadState(orderArgs.authority);
11853
+ if (typeof orderArgs.market === "string") {
11854
+ assertTargetMarketAvailable(unavailableMarkets, orderArgs.market);
11855
+ }
11856
+ const market = typeof orderArgs.market === "string" ? marketByAddress(markets, orderArgs.market) : orderArgs.market;
11857
+ validateMarketMetadata(market);
11858
+ const fundingMint = orderArgs.side === "buy" ? market.quoteMint : market.baseMint;
11859
+ assertAssetDiscoveryComplete(
11860
+ unavailableMarkets,
11861
+ allocations,
11862
+ orderArgs.authority,
11863
+ fundingMint,
11864
+ market.address
11865
+ );
11866
+ const funding = planClobOrderFunding({
11867
+ authority: orderArgs.authority,
11868
+ targetMarket: market,
11869
+ side: orderArgs.side,
11870
+ orderType: orderArgs.orderType,
11871
+ price: orderArgs.price,
11872
+ quantity: orderArgs.quantity,
11873
+ allocations,
11874
+ targetSeatIndex: orderArgs.targetSeatIndex
11875
+ });
11876
+ if (funding.shortfall > 0n) {
11877
+ throw new ClobExchangeClientError(
11878
+ "insufficient_exchange_balance",
11879
+ "exchange balance is insufficient for this order",
11880
+ {
11881
+ available: funding.exchangeAvailableAmount.toString(),
11882
+ required: funding.requiredAmount.toString(),
11883
+ shortfall: funding.shortfall.toString()
11884
+ }
11885
+ );
11886
+ }
11887
+ const sourceMarkets = [...new Set(
11888
+ funding.sources.map((source) => source.allocation.market).filter((address) => address !== market.address)
11889
+ )].map((address) => marketByAddress(markets, address));
11890
+ const [targetSeats, sourceSeatEntries] = await Promise.all([
11891
+ readMarketSeats(market),
11892
+ Promise.all(sourceMarkets.map(async (source) => [
11893
+ source.address,
11894
+ await readMarketSeats(source)
11895
+ ]))
11896
+ ]);
11897
+ validateClobOrderFundingPlanSeats({
11898
+ plan: funding,
11899
+ targetSeats,
11900
+ sourceSeatsByMarket: Object.fromEntries(sourceSeatEntries)
11901
+ });
11902
+ const wallet = await readCanonicalWalletAccount(
11903
+ orderArgs.authority,
11904
+ funding.mint,
11905
+ funding.tokenProgram
11906
+ );
11907
+ let plan = withClobProgram(buildClobFundedOrderInstructionPlan({
11908
+ plan: funding,
11909
+ targetMarket: market,
11910
+ sourceMarkets,
11911
+ walletTokenAccount: wallet.tokenAccount,
11912
+ price: orderArgs.price,
11913
+ quantity: orderArgs.quantity,
11914
+ orderType: orderArgs.orderType,
11915
+ expirationTime: orderArgs.expirationTime ?? DEFAULT_ORDER_EXPIRATION_TIME,
11916
+ clientId: orderArgs.clientId,
11917
+ discardAfterMatch: orderArgs.discardAfterMatch,
11918
+ failIfOutsideBook: orderArgs.failIfOutsideBook
11919
+ }));
11920
+ if (funding.sources.length > 0 && !wallet.exists) {
11921
+ plan = await wrapWithWalletTokenAccountInitialization({
11922
+ authority: orderArgs.authority,
11923
+ mint: funding.mint,
11924
+ tokenProgram: funding.tokenProgram,
11925
+ walletTokenAccount: wallet.tokenAccount,
11926
+ plan
11927
+ });
11928
+ }
11929
+ return {
11930
+ plan,
11931
+ /* Internal source-seat withdrawals and target-seat deposits cancel
11932
+ at the exchange-account level. Fill effects arrive from indexed
11933
+ chain state, so preparation must not predict them. */
11934
+ effects: [{
11935
+ location: "exchange",
11936
+ mint: funding.mint,
11937
+ tokenProgram: funding.tokenProgram,
11938
+ delta: -funding.requiredAmount,
11939
+ market: market.address
11940
+ }],
11941
+ market,
11942
+ funding,
11943
+ sourceMarkets,
11944
+ walletTokenAccount: wallet
11945
+ };
11946
+ }
11947
+ async function readCanonicalWalletAccount(authority, mint, tokenProgram) {
11948
+ const derived = deriveTokenAccountAddress(
11949
+ args.thruClient,
11950
+ authority,
11951
+ mint,
11952
+ tokenProgram,
11953
+ TOKEN_ACCOUNT_DEFAULT_SEED
11954
+ );
11955
+ try {
11956
+ const account = await args.thruClient.accounts.get(derived.address);
11957
+ const parsed = parseTokenAccountData(account);
11958
+ if (parsed.mint !== mint || parsed.owner !== authority) {
11959
+ throw new ClobExchangeClientError(
11960
+ "invalid_token_account",
11961
+ "canonical token account does not match the requested owner and mint",
11962
+ { tokenAccount: derived.address }
11963
+ );
11964
+ }
11965
+ return { tokenAccount: derived.address, amount: parsed.amount, exists: true };
11966
+ } catch (error) {
11967
+ if (isAccountNotFoundError(error)) {
11968
+ return { tokenAccount: derived.address, amount: 0n, exists: false };
11969
+ }
11970
+ throw error;
11971
+ }
11972
+ }
11973
+ async function readMintSymbol(mint) {
11974
+ try {
11975
+ return parseMintAccountData(await args.thruClient.accounts.get(mint)).ticker || null;
11976
+ } catch (error) {
11977
+ if (isAccountNotFoundError(error)) return null;
11978
+ return null;
11979
+ }
11980
+ }
11981
+ async function readMarketSeats(market) {
11982
+ return parseSeatArenaAccount(await args.thruClient.accounts.get(market.address)).seats;
11983
+ }
11984
+ async function wrapWithWalletTokenAccountInitialization(initArgs) {
11985
+ const derived = deriveTokenAccountAddress(
11986
+ args.thruClient,
11987
+ initArgs.authority,
11988
+ initArgs.mint,
11989
+ initArgs.tokenProgram,
11990
+ TOKEN_ACCOUNT_DEFAULT_SEED
11991
+ );
11992
+ if (derived.address !== initArgs.walletTokenAccount) {
11993
+ throw new ClobExchangeClientError(
11994
+ "invalid_token_account",
11995
+ "wallet token account is not canonical"
11996
+ );
11997
+ }
11998
+ const proof = await args.thruClient.proofs.generate({
11999
+ address: derived.address,
12000
+ proofType: STATE_PROOF_TYPE_CREATING
12001
+ });
12002
+ if (!proof.proof?.length) {
12003
+ throw new ClobExchangeClientError(
12004
+ "invalid_token_account",
12005
+ "state proof is required to initialize the wallet token account"
12006
+ );
12007
+ }
12008
+ return wrapClobPlanWithTokenAccountInitialization({
12009
+ plan: initArgs.plan,
12010
+ clobProgram: clobProgramAddress,
12011
+ initialization: {
12012
+ instructionData: createInitializeAccountInstruction({
12013
+ tokenAccountBytes: derived.bytes,
12014
+ mintAccountBytes: Pubkey$1.from(initArgs.mint).toBytes(),
12015
+ ownerAccountBytes: Pubkey$1.from(initArgs.authority).toBytes(),
12016
+ seedBytes: TOKEN_ACCOUNT_DEFAULT_SEED,
12017
+ stateProof: proof.proof
12018
+ }),
12019
+ tokenProgram: initArgs.tokenProgram,
12020
+ tokenAccount: derived.address,
12021
+ mint: initArgs.mint,
12022
+ owner: initArgs.authority
12023
+ }
12024
+ });
12025
+ }
12026
+ function withClobProgram(plan) {
12027
+ return { ...plan, programAddress: clobProgramAddress };
12028
+ }
12029
+ return {
12030
+ getAccountSnapshot,
12031
+ getWithdrawalCapacity,
12032
+ prepareDeposit,
12033
+ prepareWithdrawal,
12034
+ prepareOrder
12035
+ };
12036
+ }
12037
+ function uniqueMarketAssets(markets) {
12038
+ const assets = /* @__PURE__ */ new Map();
12039
+ for (const market of markets) {
12040
+ for (const mint of [market.baseMint, market.quoteMint]) {
12041
+ if (!mint) continue;
12042
+ assets.set(assetKey(mint, market.tokenProgram), { mint, tokenProgram: market.tokenProgram });
12043
+ }
12044
+ }
12045
+ return [...assets.values()].sort(
12046
+ (a, b) => compareText2(a.mint, b.mint) || compareText2(a.tokenProgram, b.tokenProgram)
12047
+ );
12048
+ }
12049
+ function uniqueSnapshotAssets(markets, allocations, authority) {
12050
+ const assets = new Map(
12051
+ uniqueMarketAssets(markets).map((asset) => [
12052
+ assetKey(asset.mint, asset.tokenProgram),
12053
+ asset
12054
+ ])
12055
+ );
12056
+ for (const allocation of allocations) {
12057
+ if (allocation.authority !== authority || !allocation.metadataReady || !allocation.mint) {
12058
+ continue;
12059
+ }
12060
+ assets.set(assetKey(allocation.mint, allocation.tokenProgram), {
12061
+ mint: allocation.mint,
12062
+ tokenProgram: allocation.tokenProgram
12063
+ });
12064
+ }
12065
+ return [...assets.values()].sort(
12066
+ (a, b) => compareText2(a.mint, b.mint) || compareText2(a.tokenProgram, b.tokenProgram)
12067
+ );
12068
+ }
12069
+ function marketsForAsset(markets, mint, tokenProgram) {
12070
+ return markets.filter(
12071
+ (market) => market.tokenProgram === tokenProgram && (market.baseMint === mint || market.quoteMint === mint)
12072
+ );
12073
+ }
12074
+ function chooseDepositMarket(markets, allocations, authority, mint) {
12075
+ const existingMarkets = new Set(allocations.filter((allocation) => allocation.authority === authority && allocation.mint === mint && allocation.metadataReady).map((allocation) => allocation.market));
12076
+ return markets.slice().sort(
12077
+ (a, b) => Number(existingMarkets.has(b.address)) - Number(existingMarkets.has(a.address)) || compareText2(a.address, b.address)
12078
+ )[0];
12079
+ }
12080
+ function withdrawalAllocations(allocations, markets, authority, mint, tokenProgram) {
12081
+ const marketAddresses = new Set(markets.map((market) => market.address));
12082
+ const compatible = allocations.filter(
12083
+ (allocation) => allocation.authority === authority && allocation.mint === mint && allocation.tokenProgram === tokenProgram && allocation.metadataReady && allocation.freeAmount > 0n && !(allocation.statusFlags & CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN) && marketAddresses.has(allocation.market)
12084
+ );
12085
+ if (compatible.length === 0 && marketsForAsset(markets, mint, tokenProgram).length === 0) {
12086
+ throw assetNotFound(mint);
12087
+ }
12088
+ return compatible;
12089
+ }
12090
+ async function freshWithdrawalAllocations(allocations, markets, authority, readSeats) {
12091
+ const seatsByMarket = /* @__PURE__ */ new Map();
12092
+ await Promise.all([...new Set(allocations.map((allocation) => allocation.market))].map(async (address) => {
12093
+ const market = marketByAddress(markets, address);
12094
+ seatsByMarket.set(address, await readSeats(market));
12095
+ }));
12096
+ return allocations.flatMap((allocation) => {
12097
+ const seat = seatsByMarket.get(allocation.market)?.find(
12098
+ (candidate) => candidate.seatIndex === allocation.seatIndex && candidate.seatAuthority === authority
12099
+ );
12100
+ if (!seat) return [];
12101
+ return [{
12102
+ allocation,
12103
+ amount: allocation.tokenSide === "base" ? seat.quantityBase : seat.quantityQuote
12104
+ }];
12105
+ }).filter((candidate) => candidate.amount > 0n);
12106
+ }
12107
+ function tokenSideForMint(market, mint) {
12108
+ const isBase = market.baseMint === mint;
12109
+ const isQuote = market.quoteMint === mint;
12110
+ if (isBase === isQuote) {
12111
+ throw new ClobExchangeClientError(
12112
+ isBase ? "ambiguous_asset" : "asset_not_found",
12113
+ isBase ? "market uses the same mint for both token sides" : "asset is not present in the selected market",
12114
+ { market: market.address, mint }
12115
+ );
12116
+ }
12117
+ return isBase ? "base" : "quote";
12118
+ }
12119
+ function marketByAddress(markets, address) {
12120
+ const market = markets.find((candidate) => candidate.address === address);
12121
+ if (!market) {
12122
+ throw new ClobExchangeClientError(
12123
+ "incomplete_market_metadata",
12124
+ "market metadata is unavailable",
12125
+ { market: address }
12126
+ );
12127
+ }
12128
+ return market;
12129
+ }
12130
+ function validateMarketMetadata(market) {
12131
+ if (!market.address || !market.orderArena || !market.bidsCbook || !market.asksCbook || !market.tokenProgram || !market.baseMint || !market.quoteMint || !market.baseVault || !market.quoteVault || !market.marketAuthority) {
12132
+ throw new ClobExchangeClientError(
12133
+ "incomplete_market_metadata",
12134
+ "market metadata is incomplete",
12135
+ { market: market.address || "<unknown>" }
12136
+ );
12137
+ }
12138
+ }
12139
+ function transferEffects(mint, tokenProgram, amount, market, from) {
12140
+ const to = from === "wallet" ? "exchange" : "wallet";
12141
+ return [
12142
+ { location: from, mint, tokenProgram, delta: -amount, ...from === "exchange" ? { market } : {} },
12143
+ { location: to, mint, tokenProgram, delta: amount, ...to === "exchange" ? { market } : {} }
12144
+ ];
12145
+ }
12146
+ function assetNotFound(mint) {
12147
+ return new ClobExchangeClientError(
12148
+ "asset_not_found",
12149
+ "asset is not available in any CLOB market",
12150
+ { mint }
12151
+ );
12152
+ }
12153
+ function assertTargetMarketAvailable(unavailableMarkets, targetMarket) {
12154
+ const unavailable = unavailableMarkets.find((entry) => entry.market === targetMarket);
12155
+ if (!unavailable) return;
12156
+ throw new ClobExchangeClientError(
12157
+ "incomplete_market_metadata",
12158
+ "target market metadata is unavailable",
12159
+ { market: targetMarket, cause: unavailable.reason }
12160
+ );
12161
+ }
12162
+ function isAssetDiscoveryComplete(unavailableMarkets, allocations, mint) {
12163
+ const allocationMarkets = new Set(allocations.map((allocation) => allocation.market));
12164
+ return !unavailableMarkets.some(
12165
+ (entry) => !entry.baseMint || !entry.quoteMint || entry.baseMint === mint || entry.quoteMint === mint || allocationMarkets.has(entry.market)
12166
+ );
12167
+ }
12168
+ function assertAssetDiscoveryComplete(unavailableMarkets, allocations, authority, mint, ignoredMarket) {
12169
+ const allocationMarkets = new Set(allocations.filter((allocation) => allocation.authority === authority && allocation.mint === mint).map((allocation) => allocation.market));
12170
+ const relevant = unavailableMarkets.filter(
12171
+ (entry) => entry.market !== ignoredMarket && (!entry.baseMint || !entry.quoteMint || entry.baseMint === mint || entry.quoteMint === mint || allocationMarkets.has(entry.market))
12172
+ );
12173
+ if (relevant.length > 0) throw incompleteDiscovery(relevant, mint);
12174
+ }
12175
+ function incompleteDiscovery(unavailableMarkets, mint) {
12176
+ return new ClobExchangeClientError(
12177
+ "data_source_unavailable",
12178
+ "CLOB market discovery is incomplete",
12179
+ {
12180
+ unavailableMarkets: unavailableMarkets.map((entry) => entry.market).join(","),
12181
+ ...mint ? { mint } : {}
12182
+ }
12183
+ );
12184
+ }
12185
+ function assertPositiveAmount(amount) {
12186
+ if (amount <= 0n || amount > 0xffffffffffffffffn) {
12187
+ throw new ClobExchangeClientError(
12188
+ "invalid_amount",
12189
+ "amount must be between 1 and 18446744073709551615"
12190
+ );
12191
+ }
12192
+ }
12193
+ function sortMarkets(markets) {
12194
+ return markets.slice().sort((a, b) => compareText2(a.address, b.address));
12195
+ }
12196
+ function assetKey(mint, tokenProgram) {
12197
+ return mint + "\0" + tokenProgram;
12198
+ }
12199
+ function compareText2(a, b) {
12200
+ return a < b ? -1 : a > b ? 1 : 0;
12201
+ }
12202
+ function compareBigInt(a, b) {
12203
+ return a < b ? -1 : a > b ? 1 : 0;
12204
+ }
12205
+ function errorMessage(error) {
12206
+ return error instanceof Error ? error.message : String(error);
12207
+ }
11619
12208
 
11620
12209
  // src/clob/index.ts
11621
12210
  var CLOB_INSTRUCTION_MARKET_RECORD = 0;
@@ -12242,6 +12831,6 @@ function bytesFromView(value) {
12242
12831
  throw new Error("generated view did not expose a byte buffer");
12243
12832
  }
12244
12833
 
12245
- export { ArenaHeader, ArenaHeaderBuilder, CLOB_ARENA_HEADER_SIZE, CLOB_CBOOK_EMPTY_PRICE_IN_TICKS, CLOB_CBOOK_HEADER_SIZE, CLOB_CBOOK_LEVEL_SIZE, CLOB_CBOOK_MAX_PRICE_IN_TICKS, CLOB_CBOOK_MAX_SIZE, CLOB_CLIENT_ID_SIZE, CLOB_EVENT_MARKET_CREATED, CLOB_EVENT_MARKET_STATUS, CLOB_EVENT_ORDER_CANCELLED, CLOB_EVENT_ORDER_ENTRY_REMOVED, CLOB_EVENT_ORDER_FILLED, CLOB_EVENT_ORDER_MODIFIED, CLOB_EVENT_ORDER_POSTED, CLOB_EVENT_REMOVE_REASON_EVICTED, CLOB_EVENT_REMOVE_REASON_EXPIRED, CLOB_EVENT_REMOVE_REASON_FILLED, CLOB_EVENT_REMOVE_REASON_USER, CLOB_EVENT_SEAT_ASSIGNED, CLOB_EVENT_SIDE_BUY, CLOB_EVENT_SIDE_SELL, CLOB_EVENT_TOKEN_DEPOSIT, CLOB_EVENT_TOKEN_SIDE_BASE, CLOB_EVENT_TOKEN_SIDE_QUOTE, CLOB_EVENT_TOKEN_WITHDRAW, CLOB_INSTRUCTION_CREATE_ORDER_ENTRY, CLOB_INSTRUCTION_CREATE_SEATLESS_ORDER_ENTRY, CLOB_INSTRUCTION_MARKET_CREATE, CLOB_INSTRUCTION_MARKET_RECORD, CLOB_INSTRUCTION_MARKET_SET_STATUS, CLOB_INSTRUCTION_MODIFY_ORDER_ENTRY, CLOB_INSTRUCTION_SEAT_CREATE, CLOB_INSTRUCTION_TOKEN_DEPOSIT, CLOB_INSTRUCTION_TOKEN_WITHDRAW, CLOB_MARKET_ACCOUNT_SIZE, CLOB_MAX_ATOMIC_FUNDING_SOURCES, CLOB_MODIFY_FLAG_FAIL_IF_OUT_OF_RANGE, CLOB_MODIFY_FLAG_HAS_CLIENT_ID, CLOB_MODIFY_FLAG_HAS_ORDER_ID, CLOB_NULL_INDEX, CLOB_ORDER_ENTRY_SIZE, CLOB_ORDER_FLAG_BUY, CLOB_ORDER_FLAG_HAS_CLIENT_ID, CLOB_ORDER_TYPE_ALO, CLOB_ORDER_TYPE_FOK, CLOB_ORDER_TYPE_GTC, CLOB_ORDER_TYPE_IOC, CLOB_ORDER_TYPE_MTL, CLOB_PROGRAM_ADDRESS, CLOB_SEATLESS_SEAT_IDX, CLOB_SEAT_ENTRY_SIZE, CLOB_STATUS_FLAG_DEPOSITS_FROZEN, CLOB_STATUS_FLAG_PAUSED, CLOB_STATUS_FLAG_POST_ONLY, CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN, CbookAccount, CbookHeader, CbookHeaderBuilder, CbookLevel, CbookLevelBuilder, ClientId, ClobError, ClobErrorBuilder, ClobEvent, ClobEventBuilder, ClobExchangeError, ClobInstruction, ClobInstructionBuilder, ClobProgramAccount, ClobProgramAccountBuilder, CreateOrderEntryInstruction, CreateOrderEntryInstructionBuilder, CreateSeatlessOrderEntryInstruction, CreateSeatlessOrderEntryInstructionBuilder, MarketAccountBuilder, MarketAccount as MarketAccountView, MarketCreateInstruction, MarketCreateInstructionBuilder, MarketCreatedEvent, MarketCreatedEventBuilder, MarketRecordInstruction, MarketRecordInstructionBuilder, MarketSetStatusInstruction, MarketSetStatusInstructionBuilder, ModifyOrderEntryInstruction, ModifyOrderEntryInstructionBuilder, OrderArenaAccount, OrderCancelledEvent, OrderCancelledEventBuilder, OrderEntryBuilder, OrderEntryRemovedEvent, OrderEntryRemovedEventBuilder, OrderEntry as OrderEntryView, OrderFilledEvent, OrderFilledEventBuilder, OrderModifiedEvent, OrderModifiedEventBuilder, OrderPostedEvent, OrderPostedEventBuilder, SeatArenaAccount, SeatAssignedEvent, SeatAssignedEventBuilder, SeatCreateInstruction, SeatCreateInstructionBuilder, SeatEntryBuilder, SeatEntry as SeatEntryView, TokenBalanceEvent, TokenBalanceEventBuilder, TokenTransferInstruction, TokenTransferInstructionBuilder, aggregateClobExchangeBalances, assertClobActiveSeatIndex, buildClobExchangeDepositInstructionPlan, buildClobExchangeWithdrawalInstructionPlan, buildClobFundedOrderInstructionPlan, buildOrderBookSnapshot, calculateClobOrderFundingAmount, concatClobInstructions, createMarketCreateInstruction, createMarketRecordInstruction, createMarketSetStatusInstruction, createModifyOrderEntryInstruction, createOrderEntryInstruction, createSeatCreateInstruction, createSeatlessOrderEntryInstruction, createTokenDepositInstruction, createTokenWithdrawInstruction, encodeOrderFlags, parseCbookAccount, parseClobEvent, parseClobProgramAccount, parseMarketAccount, parseOrderArenaAccount, parseSeatArenaAccount, planClobOrderFunding, validateClobOrderFundingPlanSeats, wrapClobPlanWithTokenAccountInitialization };
12834
+ export { ArenaHeader, ArenaHeaderBuilder, CLOB_ARENA_HEADER_SIZE, CLOB_CBOOK_EMPTY_PRICE_IN_TICKS, CLOB_CBOOK_HEADER_SIZE, CLOB_CBOOK_LEVEL_SIZE, CLOB_CBOOK_MAX_PRICE_IN_TICKS, CLOB_CBOOK_MAX_SIZE, CLOB_CLIENT_ID_SIZE, CLOB_EVENT_MARKET_CREATED, CLOB_EVENT_MARKET_STATUS, CLOB_EVENT_ORDER_CANCELLED, CLOB_EVENT_ORDER_ENTRY_REMOVED, CLOB_EVENT_ORDER_FILLED, CLOB_EVENT_ORDER_MODIFIED, CLOB_EVENT_ORDER_POSTED, CLOB_EVENT_REMOVE_REASON_EVICTED, CLOB_EVENT_REMOVE_REASON_EXPIRED, CLOB_EVENT_REMOVE_REASON_FILLED, CLOB_EVENT_REMOVE_REASON_USER, CLOB_EVENT_SEAT_ASSIGNED, CLOB_EVENT_SIDE_BUY, CLOB_EVENT_SIDE_SELL, CLOB_EVENT_TOKEN_DEPOSIT, CLOB_EVENT_TOKEN_SIDE_BASE, CLOB_EVENT_TOKEN_SIDE_QUOTE, CLOB_EVENT_TOKEN_WITHDRAW, CLOB_INSTRUCTION_CREATE_ORDER_ENTRY, CLOB_INSTRUCTION_CREATE_SEATLESS_ORDER_ENTRY, CLOB_INSTRUCTION_MARKET_CREATE, CLOB_INSTRUCTION_MARKET_RECORD, CLOB_INSTRUCTION_MARKET_SET_STATUS, CLOB_INSTRUCTION_MODIFY_ORDER_ENTRY, CLOB_INSTRUCTION_SEAT_CREATE, CLOB_INSTRUCTION_TOKEN_DEPOSIT, CLOB_INSTRUCTION_TOKEN_WITHDRAW, CLOB_MARKET_ACCOUNT_SIZE, CLOB_MAX_ATOMIC_FUNDING_SOURCES, CLOB_MODIFY_FLAG_FAIL_IF_OUT_OF_RANGE, CLOB_MODIFY_FLAG_HAS_CLIENT_ID, CLOB_MODIFY_FLAG_HAS_ORDER_ID, CLOB_NULL_INDEX, CLOB_ORDER_ENTRY_SIZE, CLOB_ORDER_FLAG_BUY, CLOB_ORDER_FLAG_HAS_CLIENT_ID, CLOB_ORDER_TYPE_ALO, CLOB_ORDER_TYPE_FOK, CLOB_ORDER_TYPE_GTC, CLOB_ORDER_TYPE_IOC, CLOB_ORDER_TYPE_MTL, CLOB_PROGRAM_ADDRESS, CLOB_SEATLESS_SEAT_IDX, CLOB_SEAT_ENTRY_SIZE, CLOB_STATUS_FLAG_DEPOSITS_FROZEN, CLOB_STATUS_FLAG_PAUSED, CLOB_STATUS_FLAG_POST_ONLY, CLOB_STATUS_FLAG_WITHDRAWALS_FROZEN, CbookAccount, CbookHeader, CbookHeaderBuilder, CbookLevel, CbookLevelBuilder, ClientId, ClobError, ClobErrorBuilder, ClobEvent, ClobEventBuilder, ClobExchangeClientError, ClobExchangeError, ClobInstruction, ClobInstructionBuilder, ClobProgramAccount, ClobProgramAccountBuilder, CreateOrderEntryInstruction, CreateOrderEntryInstructionBuilder, CreateSeatlessOrderEntryInstruction, CreateSeatlessOrderEntryInstructionBuilder, MarketAccountBuilder, MarketAccount as MarketAccountView, MarketCreateInstruction, MarketCreateInstructionBuilder, MarketCreatedEvent, MarketCreatedEventBuilder, MarketRecordInstruction, MarketRecordInstructionBuilder, MarketSetStatusInstruction, MarketSetStatusInstructionBuilder, ModifyOrderEntryInstruction, ModifyOrderEntryInstructionBuilder, OrderArenaAccount, OrderCancelledEvent, OrderCancelledEventBuilder, OrderEntryBuilder, OrderEntryRemovedEvent, OrderEntryRemovedEventBuilder, OrderEntry as OrderEntryView, OrderFilledEvent, OrderFilledEventBuilder, OrderModifiedEvent, OrderModifiedEventBuilder, OrderPostedEvent, OrderPostedEventBuilder, SeatArenaAccount, SeatAssignedEvent, SeatAssignedEventBuilder, SeatCreateInstruction, SeatCreateInstructionBuilder, SeatEntryBuilder, SeatEntry as SeatEntryView, TokenBalanceEvent, TokenBalanceEventBuilder, TokenTransferInstruction, TokenTransferInstructionBuilder, aggregateClobExchangeBalances, assertClobActiveSeatIndex, buildClobExchangeDepositInstructionPlan, buildClobExchangeWithdrawalInstructionPlan, buildClobFundedOrderInstructionPlan, buildOrderBookSnapshot, calculateClobOrderFundingAmount, concatClobInstructions, createClobExchangeClient, createMarketCreateInstruction, createMarketRecordInstruction, createMarketSetStatusInstruction, createModifyOrderEntryInstruction, createOrderEntryInstruction, createSeatCreateInstruction, createSeatlessOrderEntryInstruction, createTokenDepositInstruction, createTokenWithdrawInstruction, encodeOrderFlags, parseCbookAccount, parseClobEvent, parseClobProgramAccount, parseMarketAccount, parseOrderArenaAccount, parseSeatArenaAccount, planClobOrderFunding, validateClobOrderFundingPlanSeats, wrapClobPlanWithTokenAccountInitialization };
12246
12835
  //# sourceMappingURL=index.js.map
12247
12836
  //# sourceMappingURL=index.js.map