@theliem/xmarket-sdk 3.9.0 → 3.11.0

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.
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as anchor from '@coral-xyz/anchor';
2
2
  import * as _solana_web3_js from '@solana/web3.js';
3
- import { PublicKey, Transaction, Keypair, TransactionInstruction, AddressLookupTableAccount } from '@solana/web3.js';
3
+ import { PublicKey, Transaction, Keypair, TransactionInstruction, AddressLookupTableAccount, VersionedTransaction } from '@solana/web3.js';
4
4
  import BN from 'bn.js';
5
5
 
6
6
  interface ProgramIds {
@@ -617,6 +617,8 @@ declare class ClobClient {
617
617
  * remaining_accounts per NO maker (5):
618
618
  * [order_record, buyer_no_token, buyer_no_collateral, buyer_no_position, no_order_status]
619
619
  */
620
+ /** Build the match_mint_orders instruction (no signing, no sending). */
621
+ private _buildMintIx;
620
622
  private matchMintOrders;
621
623
  /**
622
624
  * MERGE: 1 YES seller (taker) + N NO sellers (makers).
@@ -627,6 +629,8 @@ declare class ClobClient {
627
629
  * [order_record, seller_no_token, seller_no_collateral, seller_no_position, no_order_status]
628
630
  * After all makers, optional 5 fee accounts.
629
631
  */
632
+ /** Build the match_merge_orders instruction (no signing, no sending). */
633
+ private _buildMergeIx;
630
634
  private matchMergeOrders;
631
635
  /**
632
636
  * Auto-detect match type and execute 2-phase:
@@ -644,6 +648,7 @@ declare class ClobClient {
644
648
  */
645
649
  matchOrders(taker: SignedOrder, makers: SignedOrder[], opts?: {
646
650
  marketOracleVault?: PublicKey;
651
+ operatorWallet?: anchor.Wallet;
647
652
  }): Promise<TxResult>;
648
653
  /**
649
654
  * High-level match: caller passes price + quantity + keypair — SDK builds,
@@ -686,7 +691,32 @@ declare class ClobClient {
686
691
  taker?: PublicKey;
687
692
  }>, decimals?: number, opts?: {
688
693
  marketOracleVault?: PublicKey;
694
+ operatorWallet?: anchor.Wallet;
689
695
  }): Promise<TxResult>;
696
+ /**
697
+ * Build an unsigned VersionedTransaction for a set of match instructions.
698
+ * Callers sign and send externally — mirrors createQuestionAdmin pattern.
699
+ */
700
+ private _buildUnsignedVtx;
701
+ /**
702
+ * Build unsigned VersionedTransaction(s) for matching orders.
703
+ *
704
+ * Mirrors createQuestionAdmin pattern — SDK registers orders internally but
705
+ * returns the match tx unsigned. BE signs with both keypairs and sends:
706
+ *
707
+ * const [vtx] = await sdk.clob.buildMatchOrdersTx(taker, makers, operatorPk, payerPk);
708
+ * vtx.sign([feePayerKeypair, operatorKeypair]);
709
+ * await connection.sendRawTransaction(vtx.serialize());
710
+ *
711
+ * Returns an array because NO-taker MINT/MERGE decomposes into N txs (one per YES maker).
712
+ * Most direct/single-pair cases return a single-element array.
713
+ *
714
+ * @param operator - Whitelisted CLOB operator pubkey (must sign)
715
+ * @param payer - Fee payer pubkey (must sign, pays tx fee + rent)
716
+ */
717
+ buildMatchOrdersTx(taker: SignedOrder, makers: SignedOrder[], operator: PublicKey, payer: PublicKey, opts?: {
718
+ marketOracleVault?: PublicKey;
719
+ }): Promise<VersionedTransaction[]>;
690
720
  fetchConfig(): Promise<ClobConfig | null>;
691
721
  fetchOrderStatus(maker: PublicKey, nonce: anchor.BN): Promise<OrderStatus | null>;
692
722
  fetchOrderRecord(maker: PublicKey, nonce: anchor.BN): Promise<{
@@ -1078,6 +1108,18 @@ declare function detectMatchType(a: Order | SignedOrder, b: Order | SignedOrder)
1078
1108
 
1079
1109
  /** Maximum u64 — approve "unlimited" amount. */
1080
1110
  declare const MAX_APPROVE_AMOUNT: BN;
1111
+ /**
1112
+ * Build a Transaction that creates YES and NO Token-2022 ATAs for a user
1113
+ * (idempotent — safe to call even if they already exist).
1114
+ *
1115
+ * Required signer: payer (fee payer). No user signature needed.
1116
+ *
1117
+ * @param condition - condition PDA
1118
+ * @param user - wallet that will own the ATAs
1119
+ * @param payer - fee payer wallet pubkey
1120
+ * @param programIds - network program IDs
1121
+ */
1122
+ declare function buildCreateUserAtasTx(condition: PublicKey, user: PublicKey, payer: PublicKey, programIds: ProgramIds): Transaction;
1081
1123
  /**
1082
1124
  * Build a Transaction that approves the CLOB config PDA to transfer collateral
1083
1125
  * (USDC) from the signer's ATA.
@@ -1099,4 +1141,4 @@ declare function buildApproveCollateralTx(collateralMint: PublicKey, signer: Pub
1099
1141
  */
1100
1142
  declare function buildApproveAllOutcomeTokensTx(condition: PublicKey, signer: PublicKey, payer: PublicKey, delegate: PublicKey, programIds: ProgramIds, amount?: BN): Transaction;
1101
1143
 
1102
- export { AccountNotFoundError, AdminClient, type AdminConfigInfo, type ClaimRecordInfo, ClobClient, type ClobConfig, type CollateralConfig, type CollateralVault, type Condition, type CreateQuestionParams, CtfClient, type CtfConfig, FEE_DENOMINATOR, FeeManagementClient, HookClient, type HookConfig, IX_SYSVAR, InvalidParamError, MAX_APPROVE_AMOUNT, MarketClient, MarketOracleClient, type MarketOracleInfo, type MatchType, type NetworkConfig, type NetworkName, OracleClient, type OracleConfig, type Order, type OrderStatus, PDA, type Position, PresaleClient, type PresaleInfo, type ProgramIds, type Question, type QuestionFee, type QuestionMarketConfig, type QuestionResult, QuestionStatus, SEEDS, type SignedOrder, type TxResult, UnauthorizedError, type UserBuyRecord, type UserClaimRecord, XMarketError, XMarketSDK, buildApproveAllOutcomeTokensTx, buildApproveCollateralTx, buildBatchedEd25519Instruction, buildOrder, buildOrderFromPrice, deserializeSignedOrder, detectMatchType, generateContentHash, generateQuestionId, getOrderSignBytes, orderAmountsFromPrice, serializeOrderToBytes, serializeSignedOrder, signOrder, signOrderWithKeypair, verifySignedOrder };
1144
+ export { AccountNotFoundError, AdminClient, type AdminConfigInfo, type ClaimRecordInfo, ClobClient, type ClobConfig, type CollateralConfig, type CollateralVault, type Condition, type CreateQuestionParams, CtfClient, type CtfConfig, FEE_DENOMINATOR, FeeManagementClient, HookClient, type HookConfig, IX_SYSVAR, InvalidParamError, MAX_APPROVE_AMOUNT, MarketClient, MarketOracleClient, type MarketOracleInfo, type MatchType, type NetworkConfig, type NetworkName, OracleClient, type OracleConfig, type Order, type OrderStatus, PDA, type Position, PresaleClient, type PresaleInfo, type ProgramIds, type Question, type QuestionFee, type QuestionMarketConfig, type QuestionResult, QuestionStatus, SEEDS, type SignedOrder, type TxResult, UnauthorizedError, type UserBuyRecord, type UserClaimRecord, XMarketError, XMarketSDK, buildApproveAllOutcomeTokensTx, buildApproveCollateralTx, buildBatchedEd25519Instruction, buildCreateUserAtasTx, buildOrder, buildOrderFromPrice, deserializeSignedOrder, detectMatchType, generateContentHash, generateQuestionId, getOrderSignBytes, orderAmountsFromPrice, serializeOrderToBytes, serializeSignedOrder, signOrder, signOrderWithKeypair, verifySignedOrder };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as anchor from '@coral-xyz/anchor';
2
2
  import * as _solana_web3_js from '@solana/web3.js';
3
- import { PublicKey, Transaction, Keypair, TransactionInstruction, AddressLookupTableAccount } from '@solana/web3.js';
3
+ import { PublicKey, Transaction, Keypair, TransactionInstruction, AddressLookupTableAccount, VersionedTransaction } from '@solana/web3.js';
4
4
  import BN from 'bn.js';
5
5
 
6
6
  interface ProgramIds {
@@ -617,6 +617,8 @@ declare class ClobClient {
617
617
  * remaining_accounts per NO maker (5):
618
618
  * [order_record, buyer_no_token, buyer_no_collateral, buyer_no_position, no_order_status]
619
619
  */
620
+ /** Build the match_mint_orders instruction (no signing, no sending). */
621
+ private _buildMintIx;
620
622
  private matchMintOrders;
621
623
  /**
622
624
  * MERGE: 1 YES seller (taker) + N NO sellers (makers).
@@ -627,6 +629,8 @@ declare class ClobClient {
627
629
  * [order_record, seller_no_token, seller_no_collateral, seller_no_position, no_order_status]
628
630
  * After all makers, optional 5 fee accounts.
629
631
  */
632
+ /** Build the match_merge_orders instruction (no signing, no sending). */
633
+ private _buildMergeIx;
630
634
  private matchMergeOrders;
631
635
  /**
632
636
  * Auto-detect match type and execute 2-phase:
@@ -644,6 +648,7 @@ declare class ClobClient {
644
648
  */
645
649
  matchOrders(taker: SignedOrder, makers: SignedOrder[], opts?: {
646
650
  marketOracleVault?: PublicKey;
651
+ operatorWallet?: anchor.Wallet;
647
652
  }): Promise<TxResult>;
648
653
  /**
649
654
  * High-level match: caller passes price + quantity + keypair — SDK builds,
@@ -686,7 +691,32 @@ declare class ClobClient {
686
691
  taker?: PublicKey;
687
692
  }>, decimals?: number, opts?: {
688
693
  marketOracleVault?: PublicKey;
694
+ operatorWallet?: anchor.Wallet;
689
695
  }): Promise<TxResult>;
696
+ /**
697
+ * Build an unsigned VersionedTransaction for a set of match instructions.
698
+ * Callers sign and send externally — mirrors createQuestionAdmin pattern.
699
+ */
700
+ private _buildUnsignedVtx;
701
+ /**
702
+ * Build unsigned VersionedTransaction(s) for matching orders.
703
+ *
704
+ * Mirrors createQuestionAdmin pattern — SDK registers orders internally but
705
+ * returns the match tx unsigned. BE signs with both keypairs and sends:
706
+ *
707
+ * const [vtx] = await sdk.clob.buildMatchOrdersTx(taker, makers, operatorPk, payerPk);
708
+ * vtx.sign([feePayerKeypair, operatorKeypair]);
709
+ * await connection.sendRawTransaction(vtx.serialize());
710
+ *
711
+ * Returns an array because NO-taker MINT/MERGE decomposes into N txs (one per YES maker).
712
+ * Most direct/single-pair cases return a single-element array.
713
+ *
714
+ * @param operator - Whitelisted CLOB operator pubkey (must sign)
715
+ * @param payer - Fee payer pubkey (must sign, pays tx fee + rent)
716
+ */
717
+ buildMatchOrdersTx(taker: SignedOrder, makers: SignedOrder[], operator: PublicKey, payer: PublicKey, opts?: {
718
+ marketOracleVault?: PublicKey;
719
+ }): Promise<VersionedTransaction[]>;
690
720
  fetchConfig(): Promise<ClobConfig | null>;
691
721
  fetchOrderStatus(maker: PublicKey, nonce: anchor.BN): Promise<OrderStatus | null>;
692
722
  fetchOrderRecord(maker: PublicKey, nonce: anchor.BN): Promise<{
@@ -1078,6 +1108,18 @@ declare function detectMatchType(a: Order | SignedOrder, b: Order | SignedOrder)
1078
1108
 
1079
1109
  /** Maximum u64 — approve "unlimited" amount. */
1080
1110
  declare const MAX_APPROVE_AMOUNT: BN;
1111
+ /**
1112
+ * Build a Transaction that creates YES and NO Token-2022 ATAs for a user
1113
+ * (idempotent — safe to call even if they already exist).
1114
+ *
1115
+ * Required signer: payer (fee payer). No user signature needed.
1116
+ *
1117
+ * @param condition - condition PDA
1118
+ * @param user - wallet that will own the ATAs
1119
+ * @param payer - fee payer wallet pubkey
1120
+ * @param programIds - network program IDs
1121
+ */
1122
+ declare function buildCreateUserAtasTx(condition: PublicKey, user: PublicKey, payer: PublicKey, programIds: ProgramIds): Transaction;
1081
1123
  /**
1082
1124
  * Build a Transaction that approves the CLOB config PDA to transfer collateral
1083
1125
  * (USDC) from the signer's ATA.
@@ -1099,4 +1141,4 @@ declare function buildApproveCollateralTx(collateralMint: PublicKey, signer: Pub
1099
1141
  */
1100
1142
  declare function buildApproveAllOutcomeTokensTx(condition: PublicKey, signer: PublicKey, payer: PublicKey, delegate: PublicKey, programIds: ProgramIds, amount?: BN): Transaction;
1101
1143
 
1102
- export { AccountNotFoundError, AdminClient, type AdminConfigInfo, type ClaimRecordInfo, ClobClient, type ClobConfig, type CollateralConfig, type CollateralVault, type Condition, type CreateQuestionParams, CtfClient, type CtfConfig, FEE_DENOMINATOR, FeeManagementClient, HookClient, type HookConfig, IX_SYSVAR, InvalidParamError, MAX_APPROVE_AMOUNT, MarketClient, MarketOracleClient, type MarketOracleInfo, type MatchType, type NetworkConfig, type NetworkName, OracleClient, type OracleConfig, type Order, type OrderStatus, PDA, type Position, PresaleClient, type PresaleInfo, type ProgramIds, type Question, type QuestionFee, type QuestionMarketConfig, type QuestionResult, QuestionStatus, SEEDS, type SignedOrder, type TxResult, UnauthorizedError, type UserBuyRecord, type UserClaimRecord, XMarketError, XMarketSDK, buildApproveAllOutcomeTokensTx, buildApproveCollateralTx, buildBatchedEd25519Instruction, buildOrder, buildOrderFromPrice, deserializeSignedOrder, detectMatchType, generateContentHash, generateQuestionId, getOrderSignBytes, orderAmountsFromPrice, serializeOrderToBytes, serializeSignedOrder, signOrder, signOrderWithKeypair, verifySignedOrder };
1144
+ export { AccountNotFoundError, AdminClient, type AdminConfigInfo, type ClaimRecordInfo, ClobClient, type ClobConfig, type CollateralConfig, type CollateralVault, type Condition, type CreateQuestionParams, CtfClient, type CtfConfig, FEE_DENOMINATOR, FeeManagementClient, HookClient, type HookConfig, IX_SYSVAR, InvalidParamError, MAX_APPROVE_AMOUNT, MarketClient, MarketOracleClient, type MarketOracleInfo, type MatchType, type NetworkConfig, type NetworkName, OracleClient, type OracleConfig, type Order, type OrderStatus, PDA, type Position, PresaleClient, type PresaleInfo, type ProgramIds, type Question, type QuestionFee, type QuestionMarketConfig, type QuestionResult, QuestionStatus, SEEDS, type SignedOrder, type TxResult, UnauthorizedError, type UserBuyRecord, type UserClaimRecord, XMarketError, XMarketSDK, buildApproveAllOutcomeTokensTx, buildApproveCollateralTx, buildBatchedEd25519Instruction, buildCreateUserAtasTx, buildOrder, buildOrderFromPrice, deserializeSignedOrder, detectMatchType, generateContentHash, generateQuestionId, getOrderSignBytes, orderAmountsFromPrice, serializeOrderToBytes, serializeSignedOrder, signOrder, signOrderWithKeypair, verifySignedOrder };
package/dist/index.js CHANGED
@@ -1619,10 +1619,10 @@ ${logs.join("\n")}`);
1619
1619
  connection.getAccountInfo(clobYesAta),
1620
1620
  connection.getAccountInfo(clobNoAta)
1621
1621
  ]);
1622
- const { createAssociatedTokenAccountIdempotentInstruction: createAssociatedTokenAccountIdempotentInstruction2 } = await import('@solana/spl-token');
1622
+ const { createAssociatedTokenAccountIdempotentInstruction: createAssociatedTokenAccountIdempotentInstruction3 } = await import('@solana/spl-token');
1623
1623
  const ixs = [];
1624
1624
  if (!yesInfo) {
1625
- ixs.push(createAssociatedTokenAccountIdempotentInstruction2(
1625
+ ixs.push(createAssociatedTokenAccountIdempotentInstruction3(
1626
1626
  this.walletPubkey,
1627
1627
  clobYesAta,
1628
1628
  clobConfig,
@@ -1631,7 +1631,7 @@ ${logs.join("\n")}`);
1631
1631
  ));
1632
1632
  }
1633
1633
  if (!noInfo) {
1634
- ixs.push(createAssociatedTokenAccountIdempotentInstruction2(
1634
+ ixs.push(createAssociatedTokenAccountIdempotentInstruction3(
1635
1635
  this.walletPubkey,
1636
1636
  clobNoAta,
1637
1637
  clobConfig,
@@ -1915,11 +1915,8 @@ ${logs.join("\n")}`);
1915
1915
  * remaining_accounts per NO maker (5):
1916
1916
  * [order_record, buyer_no_token, buyer_no_collateral, buyer_no_position, no_order_status]
1917
1917
  */
1918
- async matchMintOrders(yesSigned, noMakers, collateralMint, _feeRecipient, operatorWallet, lookupTable) {
1919
- await Promise.all([
1920
- this.registerOrderIfNeeded(yesSigned),
1921
- ...noMakers.map((m) => this.registerOrderIfNeeded(m))
1922
- ]);
1918
+ /** Build the match_mint_orders instruction (no signing, no sending). */
1919
+ async _buildMintIx(yesSigned, noMakers, collateralMint, operator, payer) {
1923
1920
  const condition = yesSigned.order.condition;
1924
1921
  const taker = yesSigned.order.maker;
1925
1922
  const takerNonce = yesSigned.order.nonce;
@@ -1967,9 +1964,9 @@ ${logs.join("\n")}`);
1967
1964
  { pubkey: hookConfig, isSigner: false, isWritable: false },
1968
1965
  { pubkey: hookProgram, isSigner: false, isWritable: false }
1969
1966
  );
1970
- const matchIx = await this.program.methods.matchMintOrders(takerNonce, fillAmount, true).accounts({
1971
- operator: operatorWallet.publicKey,
1972
- payer: this.walletPubkey,
1967
+ return this.program.methods.matchMintOrders(takerNonce, fillAmount, true).accounts({
1968
+ operator,
1969
+ payer,
1973
1970
  clobConfig,
1974
1971
  condition,
1975
1972
  taker,
@@ -1996,6 +1993,19 @@ ${logs.join("\n")}`);
1996
1993
  associatedTokenProgram: splToken.ASSOCIATED_TOKEN_PROGRAM_ID,
1997
1994
  systemProgram: web3_js.SystemProgram.programId
1998
1995
  }).remainingAccounts(remainingAccounts).instruction();
1996
+ }
1997
+ async matchMintOrders(yesSigned, noMakers, collateralMint, _feeRecipient, operatorWallet, lookupTable) {
1998
+ await Promise.all([
1999
+ this.registerOrderIfNeeded(yesSigned),
2000
+ ...noMakers.map((m) => this.registerOrderIfNeeded(m))
2001
+ ]);
2002
+ const condition = yesSigned.order.condition;
2003
+ const clobConfig = this.configPda();
2004
+ const [yesMint] = PDA.yesMint(condition, this.programIds);
2005
+ const [noMint] = PDA.noMint(condition, this.programIds);
2006
+ const clobYesAta = splToken.getAssociatedTokenAddressSync(yesMint, clobConfig, true, splToken.TOKEN_2022_PROGRAM_ID);
2007
+ const clobNoAta = splToken.getAssociatedTokenAddressSync(noMint, clobConfig, true, splToken.TOKEN_2022_PROGRAM_ID);
2008
+ const matchIx = await this._buildMintIx(yesSigned, noMakers, collateralMint, operatorWallet.publicKey, this.walletPubkey);
1999
2009
  await this._ensureClobOutcomeAtas(yesMint, noMint, clobConfig, clobYesAta, clobNoAta);
2000
2010
  const sig = await this.sendMatchTx([matchIx], lookupTable, operatorWallet);
2001
2011
  return { signature: sig };
@@ -2009,11 +2019,8 @@ ${logs.join("\n")}`);
2009
2019
  * [order_record, seller_no_token, seller_no_collateral, seller_no_position, no_order_status]
2010
2020
  * After all makers, optional 5 fee accounts.
2011
2021
  */
2012
- async matchMergeOrders(yesSigned, noMakers, collateralMint, feeRecipient, operatorWallet, lookupTable, opts) {
2013
- await Promise.all([
2014
- this.registerOrderIfNeeded(yesSigned),
2015
- ...noMakers.map((m) => this.registerOrderIfNeeded(m))
2016
- ]);
2022
+ /** Build the match_merge_orders instruction (no signing, no sending). */
2023
+ async _buildMergeIx(yesSigned, noMakers, collateralMint, operator, payer, opts) {
2017
2024
  const condition = yesSigned.order.condition;
2018
2025
  const sellerYes = yesSigned.order.maker;
2019
2026
  const takerNonce = yesSigned.order.nonce;
@@ -2066,7 +2073,7 @@ ${logs.join("\n")}`);
2066
2073
  const feeOverridePda = PDA.marketFeeOverride(condition, this.programIds)[0];
2067
2074
  const feeOverrideExists = await this.provider.connection.getAccountInfo(feeOverridePda);
2068
2075
  if (feeOverrideExists) {
2069
- const oracleVault = opts?.marketOracleVault ?? this.walletPubkey;
2076
+ const oracleVault = opts?.marketOracleVault ?? payer;
2070
2077
  remainingAccounts.push(
2071
2078
  { pubkey: this.programIds.feeManagement, isSigner: false, isWritable: false },
2072
2079
  { pubkey: PDA.feeConfig(this.feeConfigOwner, this.programIds)[0], isSigner: false, isWritable: false },
@@ -2077,9 +2084,9 @@ ${logs.join("\n")}`);
2077
2084
  }
2078
2085
  }
2079
2086
  }
2080
- const matchIx = await this.program.methods.matchMergeOrders(takerNonce, fillAmount, true).accounts({
2081
- operator: operatorWallet.publicKey,
2082
- payer: this.walletPubkey,
2087
+ return this.program.methods.matchMergeOrders(takerNonce, fillAmount, true).accounts({
2088
+ operator,
2089
+ payer,
2083
2090
  clobConfig,
2084
2091
  condition,
2085
2092
  taker: sellerYes,
@@ -2105,6 +2112,19 @@ ${logs.join("\n")}`);
2105
2112
  associatedTokenProgram: splToken.ASSOCIATED_TOKEN_PROGRAM_ID,
2106
2113
  systemProgram: web3_js.SystemProgram.programId
2107
2114
  }).remainingAccounts(remainingAccounts).instruction();
2115
+ }
2116
+ async matchMergeOrders(yesSigned, noMakers, collateralMint, _feeRecipient, operatorWallet, lookupTable, opts) {
2117
+ await Promise.all([
2118
+ this.registerOrderIfNeeded(yesSigned),
2119
+ ...noMakers.map((m) => this.registerOrderIfNeeded(m))
2120
+ ]);
2121
+ const condition = yesSigned.order.condition;
2122
+ const clobConfig = this.configPda();
2123
+ const [yesMint] = PDA.yesMint(condition, this.programIds);
2124
+ const [noMint] = PDA.noMint(condition, this.programIds);
2125
+ const clobYesAta = splToken.getAssociatedTokenAddressSync(yesMint, clobConfig, true, splToken.TOKEN_2022_PROGRAM_ID);
2126
+ const clobNoAta = splToken.getAssociatedTokenAddressSync(noMint, clobConfig, true, splToken.TOKEN_2022_PROGRAM_ID);
2127
+ const matchIx = await this._buildMergeIx(yesSigned, noMakers, collateralMint, operatorWallet.publicKey, this.walletPubkey, opts);
2108
2128
  await this._ensureClobOutcomeAtas(yesMint, noMint, clobConfig, clobYesAta, clobNoAta);
2109
2129
  const sig = await this.sendMatchTx([matchIx], lookupTable, operatorWallet);
2110
2130
  return { signature: sig };
@@ -2129,7 +2149,7 @@ ${logs.join("\n")}`);
2129
2149
  const cfg = await this.fetchConfig();
2130
2150
  if (!cfg) throw new InvalidParamError("CLOB config not found on-chain");
2131
2151
  const feeRecipient = cfg.feeRecipient;
2132
- const operatorWallet = this.provider.wallet;
2152
+ const operatorWallet = opts?.operatorWallet ?? this.provider.wallet;
2133
2153
  const alt = await this.ensureAlt(
2134
2154
  taker.order.condition,
2135
2155
  collateralMint,
@@ -2156,10 +2176,19 @@ ${logs.join("\n")}`);
2156
2176
  const allBuy = t.side === SIDE_BUY && makers.every((m) => m.order.side === SIDE_BUY);
2157
2177
  const allSell = t.side === SIDE_SELL && makers.every((m) => m.order.side === SIDE_SELL);
2158
2178
  if (!allBuy && !allSell) throw new InvalidParamError("MINT/MERGE: all orders must be same side");
2159
- if (t.tokenId !== 1) throw new InvalidParamError("MINT/MERGE: taker must be YES (tokenId=1)");
2160
- if (!makers.every((m) => m.order.tokenId === 0)) throw new InvalidParamError("MINT/MERGE: makers must be NO (tokenId=0)");
2161
- if (allBuy) return this.matchMintOrders(taker, makers, collateralMint, feeRecipient, operatorWallet, alt);
2162
- return this.matchMergeOrders(taker, makers, collateralMint, feeRecipient, operatorWallet, alt, opts);
2179
+ const takerIsYes = t.tokenId === 1 && makers.every((m) => m.order.tokenId === 0);
2180
+ const takerIsNo = t.tokenId === 0 && makers.every((m) => m.order.tokenId === 1);
2181
+ if (!takerIsYes && !takerIsNo) throw new InvalidParamError("MINT/MERGE: orders must be complementary YES+NO pair");
2182
+ if (takerIsYes) {
2183
+ if (allBuy) return this.matchMintOrders(taker, makers, collateralMint, feeRecipient, operatorWallet, alt);
2184
+ return this.matchMergeOrders(taker, makers, collateralMint, feeRecipient, operatorWallet, alt, opts);
2185
+ }
2186
+ let lastResult;
2187
+ for (const yesMaker of makers) {
2188
+ if (allBuy) lastResult = await this.matchMintOrders(yesMaker, [taker], collateralMint, feeRecipient, operatorWallet, alt);
2189
+ else lastResult = await this.matchMergeOrders(yesMaker, [taker], collateralMint, feeRecipient, operatorWallet, alt, opts);
2190
+ }
2191
+ return lastResult;
2163
2192
  }
2164
2193
  /**
2165
2194
  * High-level match: caller passes price + quantity + keypair — SDK builds,
@@ -2208,6 +2237,124 @@ ${logs.join("\n")}`);
2208
2237
  const makersSigned = sortedMakers.map(buildSigned);
2209
2238
  return this.matchOrders(takerSigned, makersSigned, opts);
2210
2239
  }
2240
+ /**
2241
+ * Build an unsigned VersionedTransaction for a set of match instructions.
2242
+ * Callers sign and send externally — mirrors createQuestionAdmin pattern.
2243
+ */
2244
+ async _buildUnsignedVtx(instructions, lookupTable, payer) {
2245
+ const { connection } = this.provider;
2246
+ const { blockhash } = await connection.getLatestBlockhash();
2247
+ const cuLimit = web3_js.ComputeBudgetProgram.setComputeUnitLimit({ units: 14e5 });
2248
+ const heapFrame = web3_js.ComputeBudgetProgram.requestHeapFrame({ bytes: 262144 });
2249
+ const message = new web3_js.TransactionMessage({
2250
+ payerKey: payer,
2251
+ recentBlockhash: blockhash,
2252
+ instructions: [cuLimit, heapFrame, ...instructions]
2253
+ }).compileToV0Message(lookupTable ? [lookupTable] : []);
2254
+ return new web3_js.VersionedTransaction(message);
2255
+ }
2256
+ /**
2257
+ * Build unsigned VersionedTransaction(s) for matching orders.
2258
+ *
2259
+ * Mirrors createQuestionAdmin pattern — SDK registers orders internally but
2260
+ * returns the match tx unsigned. BE signs with both keypairs and sends:
2261
+ *
2262
+ * const [vtx] = await sdk.clob.buildMatchOrdersTx(taker, makers, operatorPk, payerPk);
2263
+ * vtx.sign([feePayerKeypair, operatorKeypair]);
2264
+ * await connection.sendRawTransaction(vtx.serialize());
2265
+ *
2266
+ * Returns an array because NO-taker MINT/MERGE decomposes into N txs (one per YES maker).
2267
+ * Most direct/single-pair cases return a single-element array.
2268
+ *
2269
+ * @param operator - Whitelisted CLOB operator pubkey (must sign)
2270
+ * @param payer - Fee payer pubkey (must sign, pays tx fee + rent)
2271
+ */
2272
+ async buildMatchOrdersTx(taker, makers, operator, payer, opts) {
2273
+ if (makers.length === 0) throw new InvalidParamError("At least 1 maker required");
2274
+ const collateralMint = this.networkConfig.defaultCollateral.mint;
2275
+ const cfg = await this.fetchConfig();
2276
+ if (!cfg) throw new InvalidParamError("CLOB config not found on-chain");
2277
+ const feeRecipient = cfg.feeRecipient;
2278
+ const alt = await this.ensureAlt(taker.order.condition, collateralMint, taker, makers);
2279
+ const t = taker.order;
2280
+ const m0 = makers[0].order;
2281
+ const SIDE_BUY = 0;
2282
+ const SIDE_SELL = 1;
2283
+ if (t.tokenId === m0.tokenId) {
2284
+ let buySignedOrder, sellCandidates;
2285
+ if (t.side === SIDE_BUY && makers.every((m) => m.order.side === SIDE_SELL)) {
2286
+ buySignedOrder = taker;
2287
+ sellCandidates = makers;
2288
+ } else if (t.side === SIDE_SELL && makers.every((m) => m.order.side === SIDE_BUY)) {
2289
+ await Promise.all([
2290
+ this.registerOrderIfNeeded(taker),
2291
+ ...makers.map((m) => this.registerOrderIfNeeded(m))
2292
+ ]);
2293
+ const ixs2 = [];
2294
+ for (const buyMaker of makers) {
2295
+ const built = await this.buildMatchComplementaryIxs(
2296
+ buyMaker,
2297
+ [taker],
2298
+ collateralMint,
2299
+ feeRecipient,
2300
+ operator,
2301
+ opts,
2302
+ true,
2303
+ true
2304
+ );
2305
+ ixs2.push(...built);
2306
+ }
2307
+ return [await this._buildUnsignedVtx(ixs2, alt, payer)];
2308
+ } else {
2309
+ throw new InvalidParamError("COMPLEMENTARY requires one BUY and one or more SELLs on same tokenId");
2310
+ }
2311
+ await Promise.all([
2312
+ this.registerOrderIfNeeded(buySignedOrder),
2313
+ ...sellCandidates.map((m) => this.registerOrderIfNeeded(m))
2314
+ ]);
2315
+ const ixs = await this.buildMatchComplementaryIxs(
2316
+ buySignedOrder,
2317
+ sellCandidates,
2318
+ collateralMint,
2319
+ feeRecipient,
2320
+ operator,
2321
+ opts
2322
+ );
2323
+ return [await this._buildUnsignedVtx(ixs, alt, payer)];
2324
+ }
2325
+ const allBuy = t.side === SIDE_BUY && makers.every((m) => m.order.side === SIDE_BUY);
2326
+ const allSell = t.side === SIDE_SELL && makers.every((m) => m.order.side === SIDE_SELL);
2327
+ if (!allBuy && !allSell) throw new InvalidParamError("MINT/MERGE: all orders must be same side");
2328
+ const takerIsYes = t.tokenId === 1 && makers.every((m) => m.order.tokenId === 0);
2329
+ const takerIsNo = t.tokenId === 0 && makers.every((m) => m.order.tokenId === 1);
2330
+ if (!takerIsYes && !takerIsNo) throw new InvalidParamError("MINT/MERGE: orders must be complementary YES+NO pair");
2331
+ const condition = t.condition;
2332
+ const clobConfig = this.configPda();
2333
+ const [yesMint] = PDA.yesMint(condition, this.programIds);
2334
+ const [noMint] = PDA.noMint(condition, this.programIds);
2335
+ const clobYesAta = splToken.getAssociatedTokenAddressSync(yesMint, clobConfig, true, splToken.TOKEN_2022_PROGRAM_ID);
2336
+ const clobNoAta = splToken.getAssociatedTokenAddressSync(noMint, clobConfig, true, splToken.TOKEN_2022_PROGRAM_ID);
2337
+ if (takerIsYes) {
2338
+ await Promise.all([
2339
+ this.registerOrderIfNeeded(taker),
2340
+ ...makers.map((m) => this.registerOrderIfNeeded(m))
2341
+ ]);
2342
+ await this._ensureClobOutcomeAtas(yesMint, noMint, clobConfig, clobYesAta, clobNoAta);
2343
+ const ix = allBuy ? await this._buildMintIx(taker, makers, collateralMint, operator, payer) : await this._buildMergeIx(taker, makers, collateralMint, operator, payer, opts);
2344
+ return [await this._buildUnsignedVtx([ix], alt, payer)];
2345
+ }
2346
+ const vtxs = [];
2347
+ for (const yesMaker of makers) {
2348
+ await Promise.all([
2349
+ this.registerOrderIfNeeded(yesMaker),
2350
+ this.registerOrderIfNeeded(taker)
2351
+ ]);
2352
+ await this._ensureClobOutcomeAtas(yesMint, noMint, clobConfig, clobYesAta, clobNoAta);
2353
+ const ix = allBuy ? await this._buildMintIx(yesMaker, [taker], collateralMint, operator, payer) : await this._buildMergeIx(yesMaker, [taker], collateralMint, operator, payer, opts);
2354
+ vtxs.push(await this._buildUnsignedVtx([ix], alt, payer));
2355
+ }
2356
+ return vtxs;
2357
+ }
2211
2358
  // ─── Queries ─────────────────────────────────────────────────────────────────
2212
2359
  async fetchConfig() {
2213
2360
  try {
@@ -15007,6 +15154,33 @@ var XMarketSDK = class {
15007
15154
  }
15008
15155
  };
15009
15156
  var MAX_APPROVE_AMOUNT = new BN4__default.default("18446744073709551615");
15157
+ function buildCreateUserAtasTx(condition, user, payer, programIds) {
15158
+ const [yesMint] = PDA.yesMint(condition, programIds);
15159
+ const [noMint] = PDA.noMint(condition, programIds);
15160
+ const yesAta = splToken.getAssociatedTokenAddressSync(yesMint, user, false, splToken.TOKEN_2022_PROGRAM_ID);
15161
+ const noAta = splToken.getAssociatedTokenAddressSync(noMint, user, false, splToken.TOKEN_2022_PROGRAM_ID);
15162
+ const tx = new web3_js.Transaction();
15163
+ tx.feePayer = payer;
15164
+ tx.add(
15165
+ splToken.createAssociatedTokenAccountIdempotentInstruction(
15166
+ payer,
15167
+ yesAta,
15168
+ user,
15169
+ yesMint,
15170
+ splToken.TOKEN_2022_PROGRAM_ID,
15171
+ splToken.ASSOCIATED_TOKEN_PROGRAM_ID
15172
+ ),
15173
+ splToken.createAssociatedTokenAccountIdempotentInstruction(
15174
+ payer,
15175
+ noAta,
15176
+ user,
15177
+ noMint,
15178
+ splToken.TOKEN_2022_PROGRAM_ID,
15179
+ splToken.ASSOCIATED_TOKEN_PROGRAM_ID
15180
+ )
15181
+ );
15182
+ return tx;
15183
+ }
15010
15184
  function buildApproveCollateralTx(collateralMint, signer, payer, delegate, amount = MAX_APPROVE_AMOUNT) {
15011
15185
  const ownerAta = splToken.getAssociatedTokenAddressSync(collateralMint, signer, false, splToken.TOKEN_PROGRAM_ID);
15012
15186
  const approveIx = splToken.createApproveInstruction(
@@ -15073,6 +15247,7 @@ exports.XMarketSDK = XMarketSDK;
15073
15247
  exports.buildApproveAllOutcomeTokensTx = buildApproveAllOutcomeTokensTx;
15074
15248
  exports.buildApproveCollateralTx = buildApproveCollateralTx;
15075
15249
  exports.buildBatchedEd25519Instruction = buildBatchedEd25519Instruction;
15250
+ exports.buildCreateUserAtasTx = buildCreateUserAtasTx;
15076
15251
  exports.buildOrder = buildOrder;
15077
15252
  exports.buildOrderFromPrice = buildOrderFromPrice;
15078
15253
  exports.deserializeSignedOrder = deserializeSignedOrder;